Quiet Time

gensim stopword 
frozenset({'twelve', 'yourselves', 'nor', 'con', 'here', 'our', 'whatever', 'mine', 'then', 'down', 'between', 'everyone', 'eg', 'just', 'yours', 'bill', 'none', 'inc', 'itself', 'be', 'because', 'hereupon', 'toward', 'me', 'six', 'some', 'noone', 'herself', 'in', 'above', 'make', 'thru', 'whereas', 'those', 'hence', 'himself', 'them', 'unless', 'yet', 'couldnt', 'last', 'under', 'he', 'somehow', 'or', 'neither', 'five', 'thereupon', 'part', 'two', 'full', 'using', 'up', 'really', 'wherever', 'as', 'front', 'back', 'nine', 'otherwise', 'sometime', 'after', 'seem', 'someone', 'anything', 'did', 'am', 'towards', 'whom', 'across', 'from', 'whence', 'less', 'wherein', 'have', 'four', 'quite', 'without', 'per', 'and', 'its', 'didn', 'been', 'hereafter', 'before', 'interest', 'please', 'seems', 'nowhere', 'very', 'well', 'but', 'whereafter', 'cannot', 'amongst', 'must', 'namely', 'few', 'hundred', 'behind', 'others', 'whenever', 'serious', 'among', 'even', 're', 'moreover', 'upon', 'of', 'him', 'anyway', 'show', 'alone', 'call', 'to', 'keep', 'since', 'still', 'onto', 'doesn', 'other', 'too', 'un', 'would', 'if', 'describe', 'next', 'had', 'along', 'fire', 'go', 'all', 'my', 'afterwards', 'this', 'so', 'has', 'further', 'seeming', 'sometimes', 'why', 'were', 'there', 'thereby', 'least', 'again', 'they', 'almost', 'several', 'top', 'ltd', 'than', 'another', 'enough', 'beforehand', 'at', 'else', 'get', 'becoming', 'for', 'an', 'various', 'ten', 'nevertheless', 'etc', 'throughout', 'latterly', 'ie', 'mostly', 'don', 'amoungst', 'beyond', 'beside', 'same', 'such', 'nobody', 'below', 'may', 'can', 'thence', 'about', 'out', 'cant', 'that', 'much', 'used', 'perhaps', 'already', 'indeed', 'detail', 'computer', 'does', 'should', 'take', 'which', 'yourself', 'hasnt', 'every', 'also', 'being', 'although', 'thick', 'whereupon', 'name', 'doing', 'each', 'fifteen', 'thereafter', 'with', 'only', 'ever', 'see', 'most', 'own', 'formerly', 'rather', 'de', 'you', 'us', 'she', 'we', 'km', 'when', 'during', 'eleven', 'however', 'regarding', 'against', 'first', 'are', 'together', 'once', 'on', 'often', 'always', 'whether', 'becomes', 'not', 'became', 'anywhere', 'though', 'was', 'sixty', 'who', 'the', 'co', 'besides', 'any', 'never', 'give', 'former', 'around', 'both', 'amount', 'more', 'themselves', 'one', 'empty', 'thin', 'whose', 'by', 'whither', 'could', 'will', 'find', 'whole', 'hers', 'say', 'therefore', 'hereby', 'fill', 'these', 'done', 'through', 'thus', 'her', 'sincere', 'until', 'what', 'might', 'how', 'his', 'latter', 'meanwhile', 'nothing', 'a', 'move', 'side', 'somewhere', 'their', 'is', 'found', 'become', 'elsewhere', 'over', 'ourselves', 'i', 'put', 'no', 'whereby', 'anyone', 'cry', 'eight', 'myself', 'ours', 'everything', 'except', 'forty', 'it', 'your', 'system', 'many', 'off', 'where', 'while', 'within', 'due', 'now', 'third', 'herein', 'twenty', 'whoever', 'into', 'do', 'bottom', 'everywhere', 'something', 'via', 'either', 'fify', 'seemed', 'anyhow', 'three', 'kg', 'therein', 'made', 'mill'})

scikit-learn stopword 
frozenset({'already', 'ltd', 'until', 'on', 'besides', 'becoming', 'de', 'few', 'same', 'which', 'in', 'made', 'whom', 'though', 'being', 'front', 'whereby', 'whose', 'who', 'along', 'anyone', 'have', 'now', 'been', 'often', 'else', 'her', 'formerly', 'found', 'co', 'ever', 'can', 'mill', 'yet', 'hereby', 'always', 'around', 'only', 'eg', 'its', 'thereupon', 'there', 'at', 'nevertheless', 'mine', 'nine', 'give', 'becomes', 'hers', 'see', 'wherein', 'neither', 'nobody', 'sometime', 'six', 'too', 'behind', 'someone', 'himself', 'she', 'down', 'afterwards', 'about', 'with', 'anyway', 'fire', 'couldnt', 'they', 'their', 'first', 'somehow', 'un', 'herein', 'well', 'less', 'elsewhere', 'the', 'cannot', 'myself', 'would', 'therefore', 'thick', 'ours', 'some', 'empty', 'our', 'again', 'con', 'name', 'bottom', 'five', 'interest', 'were', 'me', 'may', 'next', 'per', 'seem', 'through', 'almost', 'below', 'from', 'thru', 'to', 'of', 'twenty', 'both', 'cry', 'every', 'somewhere', 'hence', 'under', 'cant', 'why', 'everyone', 'among', 'fill', 'is', 'amoungst', 'these', 'fifteen', 'become', 'perhaps', 'even', 'etc', 'part', 'than', 'ie', 'much', 'third', 'indeed', 'was', 'yours', 'any', 'another', 'together', 'whole', 'each', 'if', 'show', 'them', 'whatever', 'describe', 'whereafter', 'eleven', 'and', 'thereafter', 'has', 'three', 'it', 'herself', 'amount', 'up', 'everything', 'before', 'sincere', 'him', 'how', 'that', 'call', 'off', 'seemed', 'we', 'yourself', 'noone', 'while', 'into', 'very', 'several', 'across', 'above', 'be', 'but', 'not', 'could', 'therein', 'ourselves', 'due', 'once', 'hereafter', 'beside', 'hundred', 'no', 'for', 'keep', 'one', 'upon', 'after', 'other', 'or', 'amongst', 'last', 'others', 'serious', 'this', 'a', 'where', 'meanwhile', 'wherever', 'whether', 'mostly', 'an', 'full', 'forty', 'via', 'take', 'eight', 'side', 'you', 'anything', 'more', 'nothing', 'between', 'inc', 'move', 'whoever', 'never', 'am', 'because', 'beyond', 'either', 'except', 'former', 'namely', 'please', 'should', 'without', 'those', 'however', 'two', 'will', 'also', 'done', 'many', 'nor', 'out', 'detail', 'enough', 'thin', 'your', 'latterly', 'whence', 'as', 'yourselves', 'since', 'seems', 'thence', 'put', 'had', 'towards', 'moreover', 'throughout', 'further', 'so', 'toward', 'twelve', 'bill', 'during', 'against', 'still', 'alone', 'us', 'might', 'here', 'whereupon', 'nowhere', 'anywhere', 'within', 'hereupon', 'sometimes', 'became', 'over', 'i', 'onto', 'what', 're', 'although', 'he', 'itself', 'rather', 'latter', 'my', 'go', 'most', 'top', 'seeming', 'fifty', 'his', 'back', 'by', 'own', 'ten', 'then', 'must', 'when', 'none', 'everywhere', 'get', 'are', 'hasnt', 'least', 'system', 'sixty', 'beforehand', 'find', 'such', 'whither', 'anyhow', 'themselves', 'thus', 'something', 'whenever', 'four', 'thereby', 'all', 'whereas', 'otherwise', 'do'})

spacy stopword 
{'why', 'does', 'latterly', 'mostly', 'but', 'otherwise', 'during', 'ourselves', 'forty', 'yourselves', 'hereupon', 'only', 'into', 'she', 'become', 'can', 'two', 'ten', 'ever', 'within', 'call', 'go', 'hundred', 'under', 'up', 'thru', 'well', 'nobody', 'is', 'noone', 'elsewhere', 'must', 'nothing', 'own', 'such', 'thereafter', 'me', 'any', 'several', 'behind', 'beside', 'his', 'your', 'have', 'therein', 'until', 'itself', 'should', 'moreover', 'everything', 'been', 'if', 'cannot', 'show', 'thereupon', 'nowhere', 'this', 'who', 'fifty', 'amount', 'an', 'however', 'since', 'as', 'that', 'whither', 'below', 'please', 'all', 'do', 'anything', 'else', 'used', 'very', 'third', 'name', 'various', 'either', 'i', 'our', 'when', 'will', 'sometimes', 'front', 'done', 'thus', 'herein', 'seemed', 'yet', 'indeed', 'whose', 'least', 'serious', 'last', 'still', 'much', 'another', 'along', 'him', 'nevertheless', 'again', 'many', 'none', 'he', 'nor', 'quite', 'alone', 'although', 'mine', 'same', 'ours', 'take', 'twelve', 'yours', 'meanwhile', 'full', 'due', 'its', 'hereafter', 'thereby', 'becomes', 'has', 'thence', 'toward', 'by', 'himself', 'never', 'fifteen', 'wherein', 'in', 'besides', 'whereby', 'be', 'each', 'could', 'from', 'together', 'would', 'hereby', 'whereafter', 'whether', 'down', 'eleven', 'formerly', 'were', 'and', 'top', 'others', 'see', 'whole', 'less', 'my', 'anyway', 'even', 'keep', 'both', 'over', 're', 'ca', 'side', 'there', 'namely', 'regarding', 'how', 'anyhow', 'upon', 'bottom', 'further', 'wherever', 'hence', 'then', 'more', 'across', 'against', 'five', 'somehow', 'herself', 'whenever', 'someone', 'them', 'had', 'often', 'yourself', 'seem', 'among', 'themselves', 'put', 'are', 'out', 'whoever', 'myself', 'enough', 'doing', 'beyond', 'off', 'those', 'while', 'no', 'onto', 'say', 'just', 'became', 'now', 'make', 'may', 'what', 'made', 'after', 'above', 'part', 'neither', 'everywhere', 'back', 'four', 'hers', 'per', 'first', 'perhaps', 'also', 'too', 'to', 'where', 'without', 'you', 'every', 'afterwards', 'seems', 'on', 'they', 'using', 'becoming', 'around', 'did', 'us', 'except', 'with', 'three', 'through', 'somewhere', 'seeming', 'a', 'towards', 'really', 'was', 'than', 'whatever', 'already', 'always', 'beforehand', 'because', 'anywhere', 'whereupon', 'rather', 'anyone', 'other', 'six', 'sixty', 'being', 'these', 'which', 'her', 'once', 'here', 'about', 'at', 'eight', 'some', 'for', 'latter', 'between', 'whereas', 'former', 'we', 'of', 'the', 'whence', 'something', 'so', 'it', 'most', 'few', 'unless', 'give', 'almost', 'twenty', 'amongst', 'before', 'sometime', 'or', 'their', 'not', 'therefore', 'nine', 'get', 'one', 'empty', 'move', 'whom', 'everyone', 'via', 'throughout', 'though', 'might', 'next', 'am'}

nltk stopword 
['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]

from wordcloud import WordCloud, STOPWORDS
print(STOPWORDS)

{"he'll", 'they', 'while', 'with', "there's", 'however', 'since', 'could', "why's", 'about', 'during', 'just', "we'd", 'she', 'below', "let's", 'but', 'very', "they're", 'k', 'been', 'can', 'than', 'was', 'a', 'our', "weren't", "when's", "where's", 'by', 'his', "she'd", 'doing', 'me', 'then', 'this', "i'll", "you've", 'yourself', 'before', 'more', 'should', "wasn't", "can't", 'who', 'through', 'were', 'did', 'do', 'their', 'ourselves', 'whom', 'at', 'nor', 'on', 'shall', 'having', 'had', 'her', 'it', "hasn't", "we're", 'off', 'what', 'them', "that's", 'he', 'as', 'these', 'i', 'why', 'or', 'out', 'has', 'most', "aren't", 'be', 'all', 'com', "didn't", 'like', 'between', "we've", "i'd", 'are', 'how', "hadn't", "they've", "shan't", 'herself', 'of', "mustn't", 'there', 'yours', 'hers', 'until', "doesn't", "wouldn't", 'each', "i'm", 'once', 'the', 'myself', 'such', 'again', "he's", 'for', 'no', 'only', "don't", 'my', "they'd", 'too', "you'd", 'ever', 'ours', 'few', "couldn't", 'does', 'if', "she's", "he'd", 'www', "they'll", "you're", 'other', 'being', 'to', 'any', 'your', 'which', 'get', 'over', 'from', 'its', 'himself', 'in', 'ought', 'have', "haven't", 'down', 'him', 'where', "we'll", "won't", "shouldn't", 'http', "i've", 'some', "isn't", 'those', 'yourselves', 'would', 'itself', "who's", 'after', 'also', 'because', 'here', 'own', 'we', 'cannot', 'themselves', 'an', 'further', 'am', "here's", 'and', 'above', 'otherwise', 'you', "how's", "it's", 'same', 'not', 'that', 'against', 'is', 'when', 'else', 'r', "you'll", "what's", 'theirs', 'under', 'both', 'up', "she'll", 'so', 'into'}


'PYTHON' 카테고리의 다른 글

gcp를 이용해서 jupyter notebook / jupyter lab 서버 만들기  (0) 2018.08.27
9장. 객체와 클래스 (가장 중요한 단원)  (0) 2017.09.10
8장. 모듈  (0) 2017.09.10
7장. 함수  (0) 2017.09.10
6장. if 문과 loop문 (p126)  (0) 2017.09.10


gcp를 이용해서 jupyter lab 서버 만들기

구글 가상 인스턴스는 카드 등록하면 1년간 크레딧 범위 안에서 무료로 사용 할 수 있다
gcp를 이용해서 어디서나 접근 가능한 jupyter lab



구글 클라우드 플랫폼 접속




왼쪽위 석삼자 三모양 누르고 




Compute Engine > VM instance > (플러스모양) Create instance



위에 보이는 것은 기존에 만들어 놓은것 
구글 가상 인스턴스는 카드 등록하면 1년간 크레딧 범위 안에서 무료로 사용 할 수 있고 무료기간 현재 147일 남음 


Centos 7,  30기가로 새로 만드려고 했으나 이름 규칙에 어긋난다고함 소문자 , 숫자 , 하이픈만 허용됨

 
Centos 7 , HDD 30 GB






Compute Engine > VM instance에서 해당 vm 머신에서 ssh 를 누르면(5번째그림 참고 vm맨 오른쪽에 버튼이 있음) 웹콘솔로 ssh명령창이 나옴
다음 명령어를 입력



sudo yum install wget # 아나콘다 다운 받기위해
sudo yum install bzip2  # 설치 안하면 아나콘다 설치중 에러
sudo wget https://repo.continuum.io/archive/Anaconda3-4.2.0-Linux-x86_64.sh # konlp 사용을 위해 파이썬 3.5버전설치 다른 버전 필요시 구글에 python archives 를검색
sh Anaconda3-4.2.0-Linux-x86_64.sh # 아나콘다 설치

vi .bashrc

# 설치후 안내되는 파이썬 경로를 .bashrc에 추가 
source .bashrc # 실행

jupyter notebook --generate-config # 주피터 노트북 설정 파일 생성

vi <안내되는경로>/.jupyter/jupyter_notebook_config.py # 주피터 노트북 설정 파일 편집
vi 편집기로 위 파일을 연다음 아래 내용을 입력 
c = get_config()

c.IPKernelApp.pylab = 'inline'

c.NotebookApp.open_browser = False

c.NotebookApp.token = ''

pip install konlp 
pip install jupyterlab 등 필요한 패키지 설치


vm 인스턴스의 네트워크 설정에서 외부에서 해당 포트 접속가능 하도록 설정하고 

nohup jupyter lab --ip=0.0.0.0 --port=8888 --no-browser & # 콘솔창을 닫아도 서버가 꺼지지 않게 

<exteranl IP >:8888 로 웹브라우저 접속하면 완성













'PYTHON' 카테고리의 다른 글

English stopword , 영어 불용어  (0) 2018.09.18
9장. 객체와 클래스 (가장 중요한 단원)  (0) 2017.09.10
8장. 모듈  (0) 2017.09.10
7장. 함수  (0) 2017.09.10
6장. if 문과 loop문 (p126)  (0) 2017.09.10



ㅁ■ 객체와 클래스 (가장 중요한 단원) 

  • 9장 목차
  1. 객체와 클래스
  2. 클래스의 정의
  3. __init__() 메소드를 이용한 초기화작ㅇ업
  4. self에 대한 이해 
  5. 정적 메소드와 클래스 메소드 
  6. 클래스 내부에게만 ㅇ려려있는 프라이빗 멤버
  7. 상속
  8. 오버라이딩
  9. __call()__ 메소드 
  10. for문으로 순회를 할 히 있는 객체 만들기 
  11. 추상기반 클래스 
■ 9.1 객체와 클래스
객체(object) = 속성(attribute) + 기능 
    자동차          ↑            ↑
               자동차 색깔  전진, 후진,좌회전,우회전
               바퀴의 크기

코드로 구현을 하면 ? 

객체      =      변수      +      함수 

예제 :
class Car
     def __init__(self):
          self.color =0xFF0000 # 자동차의 색
          self.whell_size = 16
          self.displacement = 2000 # 엔진 배기량 


     def forward(self) : # 전진하는 기능
          pass
     def backward(self) : # 후진하는 기능
          pass
     def turn_right(self): # 우회전 하는 기능 
          pass

     def turn_left(self): #좌회전 하는 기능
          pass

if __name__ == '__main__' : # 메인 모듈일때만 아래의 스크립트를 실행해라

     my_car = Car() # 클래스를 가지고 인스턴스화 하는 코드
                    # Car() 클래스로 my_car라는 객체를 생성했다. 

     print('0x{:02X}'.format(my_car.color))
     print(my_car.whell_size))
     print(my_car.displacement)

     my_car.forward()                    # my_car 의 메소드(기능) 를 호출 
     my_car.backward()
     my_car.turn_left()
     my_car.turn_right()

■ 9.2. 클래스의 정의 


     클래스(자료형) ----> 객체(변수) 

     위의 클래스는 자료형이고 아직 객체가 되지 않았다
                    붕어빵 틀     붕어빵 (인스턴스, 실체라고 얘기함) 
                    (속성: 붕어빵 색
                           붕어빵 앙금(팥, 슈크림)

                     기능: 왼쪽으로 가라 오른쪽으로 가라 
     my_car = Car()           # Car() 클래스에 의해서 my_car라는 객체가 생성됨 인스턴스화 됨


객체 = 속성 + 기능 
      (변수)  (함수)
 
  • 코드 설명 :
     
    def __init__(self): 

1. __init__ ? 객체가 생성될때 호출되는 메소드로서 객체의 초기화를 담당한다
2.self      ? 메소드의 첫번째 매개변수로 객체 자신임을 나타냄 
3.my_car = Car() ? car() 생성자는 car 클래스의 인스턴스를 생성하여 반환한다. 
   ↑         
 인스턴스    생성자
   (실체)    (설계도)


■ 9.3 __init__() 메소드를 이용한 초기화 

클래스의 생성자가 호출이되면 내부적으로 두개의 메소드가 호출된다.
  1. __new__()   : 클래스의 인스턴스를 만드는 역할 ( 내부적으로 자동으로 호출된다.)
  2. __init__()  : 객체가 생성될  대 객체를 초기화하는 역할 
  • 만약 __init__() 메소드를 클래스 생성할 때 지정안하며 ㄴ어떻게 되는지 테스트 

1.__init__() 메소드를 지정 안 했을때

class ClassVar:
     text_list = [] # 클래스의 정의 싷점에서 바로 메모리에 할당됨 
     
     def add(self,text):
          self.text_list.append(text) 

     def print_list(self):
          print(self.text_list)

if __name__ == '__main__':
     a = ClassVar()

ㅁ■ 객체와 클래스 (가장 중요한 단원) 

  • 9장 목차
  1. 객체와 클래스
  2. 클래스의 정의
  3. __init__() 메소드를 이용한 초기화작ㅇ업
  4. self에 대한 이해 
  5. 정적 메소드와 클래스 메소드 
  6. 클래스 내부에게만 ㅇ려려있는 프라이빗 멤버
  7. 상속
  8. 오버라이딩
  9. __call()__ 메소드 
  10. for문으로 순회를 할 히 있는 객체 만들기 
  11. 추상기반 클래스 


9.4 self 에 대한 이해 
" 클래스에서 사용하는 최도 매개변수인데 self는 자기 자신을 가리킨다"

9.5 정적 메소드와 클래스 메소드 
1.인스턴스 메소드   : 로봇의 팔이 잘 작동하는지 로봇을 만들어노혹 작동해 보면 확이하는 메소드
2.클래스(정적) 메소드 : 로봇의 팔이 잘 작동하느니즈이 확인을 로봇을 만들지 않고 어떻게 하면 로봇팔이 움진인다는                     프로그램 코드를 실행히셬 확인하는 메소드 



class Calculator:
    @staticmethod
    def plus(a, b):
        return a+b

    @staticmethod
    def minus(a, b):
        return a-b

    @staticmethod
    def multiply(a, b):
        return a*b

    @staticmethod        
    def divide(a, b):
        return a/b
        
if __name__ == '__main__':        
    print("{0} + {1} = {2}".format(7, 4, Calculator.plus(7, 4)))
    print("{0} - {1} = {2}".format(7, 4, Calculator.minus(7, 4)))
    print("{0} * {1} = {2}".format(7, 4, Calculator.multiply(7, 4)))
    print("{0} / {1} = {2}".format(7, 4, Calculator.divide(7, 4)))



■ 어제 배웠던 내용 복습

   1. 클래스 와 객체
   (붕어빵틀)  (붕어빵)

      객체의 구성요소 2가지
      1. 속성(변수)
      2. 기능(함수)



   class gorilla   class pingpong
   속성: 고릴라 색깔   공과 판의 색깔, 위치
   기능: 고릴라 기능   좌로 이동, 우로 이동
   gorilla() = gorilla() -----> 생성자   pingpoing = pingpoing()

   2. 객체를 초기화 해주기 위해서 필요한 키워드, 메소드?

         self, __init__


■ 9.6 클래스 내부에게만 열려있는 프라이빗 멤버(pg200)

* 파이썬에서 사용하는 멤버 2가지

   1. public member : 클래스 안에서든 밖에서든 접근 가능 한 멤버

     예: 접두사가 두개의 밑줄이고 접미사도 두개의 밑줄이면
   __number__

   2. private member : 클래스 안에서만 접근 가능한 멤버
            클래스의 사생활을 지켜줘야할 때 요긴하게 사용됨

     예: 접두사가 두개의 밑줄이고 접미사는 없거나 하나의 밑줄

   __number
   __number_



6. 클래스 내부에게만 열려있는 프라이빗 멤버
      ○ 파이썬에서 사용하는 멤버 2가지
         i. public member - 클래스 안에서든 밖에서든 접근 가능한 멤버
            □ 접두사가 두개의 밑줄이고 접미사도 두개의 밑줄이면 퍼블릭 멤버, __number__

         ii. private member - 클래스 안에서만 접근 가능한 멤버, 클래스의 사생활을 지켜줘야할 때 요긴함
            □ 접두사가 두개의 밑줄이고 접미사는 없거나 하나의 밑줄, __number_ / __number

   • 예제 - 퍼블릭 멤버로 사용했을 경우

           class yourclass:
               pass

           class myclass:
               def __init__(self):
                   self.message = "Hello"

               def some_method(self):
                   print(self.message)

           obj = myclass()
           obj.some_method()  #메소드를 실행했기 때문에 출력이 된 것, 객체명.기능 --> 실행
           print(obj.message)  #따로 message라는 변수의 내용을 출력, print해서 본 것


   • 예제 - 프라이빗 멤버로 사용했을 경우

           class yourclass:
               pass

           class myclass:
               def __init__(self):
                   self.message = "Hello"
                   self.__private = "private"

               def some_method(self):
                   print(self.message)
                   print(self.__private)

           obj = myclass()
           obj.some_method()
           print(obj.message)
           print(obj.__private)  #프라이빗이라서 에러가 난다.

9.7 상속

   • 상속 : 클래스들끼리 유산(기능) 을 물려주는 것
      클래스  ---------------------------------> 클래스
      부모                  유산(기능)                자식  으로 물려주는 것

   • 상속을 받게 되면 자식 클래스에 부모 기능을 코딩하지 않아도 됨.
      학습시키는 클래스(짝꿍) --------------------------> 나는 핑퐁게임 클래스만 만들고 나머지는 상속 받아서 사용

   • 예제1
      class father :
def base_method(self) :


클래스 부모 ------------------- 클래스 자식 상속

상속을 받게되면 부모의 기능을 굳이 자식 클래스에 코딩하지 않아도 된다.


학습 시키는 클래스 (짝꿍) -------------------------> 나는 핑퐁게임 클래스 
                          머신러닝 기능 유산

예제 1 : 

class father 
     def base_mothod(self) :
          print("hello")

class child(father):
     pass

father = father()

father.base_method()

child = child() 
child.base_method()


예제2. __init__ 메소드를 가지고 실행하는데 부모와는 틀리게 자식에message라는 속성이 없어서 상속을 시키고 싶을때?


class father:
     def __init__(self):
          print("hello~~")
          self.message="Good Morning"

class child(father):
     def __init__(self):
          print("hello~~ I am child")

child = child()
print(child.message) <==========애기는 굿모닝 못하네여





class father:
     def __init__(self):
          print("hello~~")
          self.message="Good Morning"

class child(father):
     def __init__(self):
          father.__init__(self) # 파이썬은 암묵적인 것을 싫어하고 명시적인것을 좋아한다.
          프로그래머가 명시적으로 클래스의 초기화 메소드를 호출해주길 원함
          print("hello~~ I am child")

child = child()
print(child.message)

■ super()

child = child() 
print(child.message)

super() 는 부모클래스의 객체 역할을 하는 내장 함수.
사실상 super() 함수의 반환값을 상위객체로 지정한다 다른 클래스로 교체되거나 수정되어도 파생클래스가
받는 영향을 최소화 할 수 있다. 

class father:
     def __init__(self):
          print("hello~~")
          self.message="Good Morning"

class child(father):
     def __init__(self):
          #father.__init__(self)
          super.__init__()

          print("hello~~ I am child")

child = child()
print(child.message)

■ 다중상속

다중 상속이란 두개 이상의 클래스를 상속 받는것을 말한다
이 경우에는 두 클래스의 모든 속성을 물려받게된다
이는 하나의 자식 클래스가 두개 이상의 부모 클래스를 가지는 것이라고 할 수 있다. 


          father1            father2
               ↘              ↙
                    child
예제 1:

class father1:
     def func(self):
          print("지식")

class father2:
     def func(self):
          print("지혜")

class child(father1,father2):
     def childfunc(self):
father1.func(self)
father2.func(self)

objectchild = child()
objectchild.childfunc()
objectchild.func() # 결과 : 지식 (물려 받은 순서 우선순위 출력 father1 의 지식이 출력된다.)

■ 그런데 둘다 출력하기 싫고 하나만 출력하고 싶어서 

                 grandfather 

                          

          father1            father2

                ↘           ↙

                 grandchild



예제 : 
class grandfather:
     def __init__ (self):
          print("튼튼한 두팔")

class father1(grandfather):
     def __init__ (self):
          grandfather.__init__(self)
          print("지식")

class father1(grandfather):
     def __init__ (self):
          grandfather.__init__(self)
          print("지혜")

class grandchild(father1, father2):
     def __init__(self):
          father1.__init__(self)
          father2.__init__(self)
          print("난 행복해")

grandchild = grandchild()
결과 :
튼튼한 두팔
지식
튼튼한 두팔
지혜
난 행복해

다이아몬드 상속을 받았더니 그만 팔이 4개가 되어부럿당!

문제166. (점심시간 문제) 다시 팔이 2개가 되게 하시오 

class grandfather:
     def __init__ (self):
          print("튼튼한 두팔")

class father1(grandfather):
     def __init__ (self):
          super().__init__()
          print("지식")

class father2(grandfather):
     def __init__ (self):
          super().__init__()
          print("지혜")

class grandchild(father1, father2):
     def __init__(self):
          super().__init__()
          print("난 행복해")

grandchild = grandchild()




6     클래스내부에게만 열려잇느 프라이빗 멤버
7     상속
8     오버라이딩
9     __call()__메소드
10    for 문으로 순회를 하룻 잇는 객체 만들기
11    추상 기반 클래스

9.6 오버라이딩

~ 보다 우선한다는 뜻이다
부모로 부터 상속받은 메소드를 다시 Override(재정의) 하겠다.

예제: 
class grandfather:
     def __init__(self):
          print("튼튼한 두팔")
class father2(grandfather):
     def __init__(self):
          print("지혜")

father2 = father2()
지혜도 주요지만 건강도 물려받고싶다면
class grandfather:
     def __init__(self):
          print("튼튼한 두팔")
class father2(grandfather):
     def __init__(self):
          super().__init__()
          print("지혜")

father2 = father2()

■ super() 에 대해서?
1.super()를 이용하면 부모클래스의 멤버에 접근을 할 수 있따.
2.super()를 이용하면 부모 클래스 명이 변경되어도 일일이 코드를 고치는 수고를 줄일 수 있다.
3.super()를 이요함녀 죽음의 다이아몬드 상속을 피할 수 있다. 

aa■ 9.6 데코레이터 사용법 
데코레이터의 사전적 의미? 꾸미다
데코레이터는 함 수를 꾸며주는 함수 
데코레이터는 함수의 능력을 확장 시켜준다. 
 
어떤 동작을 수행하기 전에 @ 로 시작하는 키워드를 사용해서 수행한다.

  • 데코레이터의 중요한 2가지 기능
  • 1. 함수를 강력하게 해준다.
  • 2. 공통적으로 사용하는 코드를 쉽게 관리하기 위해서 사용한다


  • 파이썬 함수의 4가지 특징
  • 1. 변수에 할당 할 수 있다.
  • 2. 다른 함수내에서 정의 될 수 있다. 
  • 3. 함수의 인자(매개변수)값으로 전달될 수 있다.
  • 4. 함수의 반환값이 될 수 있다. 


  1. 함수를 !!!  변수에 할당!!!!

def greet(name):
     return "Hello {} ".format(name) 

greet_someone = greet # 함수를 변수에 할당
print(greet_someone("scott")) 

  1. 다른 함수내에서 정의 할수 있어!!!!!
def greet(name):
    def greet_message():
       return 'Hello'
    return "{}  {}".format(greet_message(),name)

print(greet("scott"))

  1. 함수의 인자값으로 전달 될 수 있다!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
예: 
def greet(name):
     return "Hello {}".format(name)

def change_name_greet(func):
     name = "king"
      return func(name)

print( change_name_greet(greet))


  1. 함수의 반환값이 될 수 있다.


def greet (name):
     return "Hello {}".format(name)

 def uppercase (func):
     def wrapper(name):
          result = func(name)
          return result.upper()
     return wrapper

new_greet = uppercase(greet) ("scott")
print(new_greet)
print(new_greet("scott"))
문제167. 이름을 입력하고 함수를 실행하면
          해당하는 사원들의 직업이 소문자로 출력되는 함수를 생성하시오 !

함수1. 이름을 입력했을때 직업이 출력되는 함수 (find_job)
함수2. 문자를 입력했을때 소문자로 출력하는 함수 (lower_case)



def find_job(name):
    import pandas as pd
    emp = pd.DataFrame.from_csv("d:/data/emp.csv")
    job = emp[['job']][emp['ename'] == name].values[0][0]

    return job


def lowercase(func):
    def wrapper(name):
        result = func(name)
        return result.lower()

    return wrapper



new_find_job = lowercase(find_job)

print(new_find_job('SCOTT'))



■ 데코레이터 표현법을 보기전에 먼저 데코레이터와 같은
역할을 하는 함수를 생성

class greet(object):
    current_user = None
    def set_name(self,name): # current_user 라는 변수인 속성은 선언
        if name =='admin': #name 에 admin 이라는 문자를 담고
            self.current_user = name
        else:                  #admin 이 아니라면 권한이 없다는 에러를
            raise Exception("권한이 없네요") #발생시키는 함수

    def get_greeting(self,name): #name 이라는 매개변수에 admin 이
        if name == 'admin':  # 입력이 됬다면
            return "Hello {}".format(self.current_user)

                    #Hello 와 current_user 를 리턴하는
                    #함수


실행방법:

greet = greet()
greet.set_name('admin')
print(greet.get_greeting('admin'))

'Error cuz of object is not callable'

greet = greet()
greet.set_name('scott')
print(greet.get_greeting('scott')) # scott 은 안되거든?

문제168.어드민만 헬로 출력되게하라 

class greet(object):          # current_user 라는 변수인 속성을 선언

     current_user = None     # name에 admin이라는 문자가 들어오면
     def set_naem(self,name):     #current_user 에 admin 이라는 문자를 담고
          if name == 'admin':
               self.currnet_user = name
          else:                #admin이 아니라면 권한이 없다는 에러를 발생시킴
               raise Exception("권한이 없네요")

     def get_greeting(self,name):     # name이라는 매개변수에 admin이 입력되면
          if name == 'admin':
               return "Hello {}".format(self.current_user)
                                       # Hello와 current_user를 리턴하는 함수 
                                       

실행방법 :
greet = greet()
greet.set_name('admin')
print(greet.get_greeting('admin') )


위의 코드에서 중복되는 부분 즉 admin이 맞는지 확인하는 공통적인 코드를 하나의 함수로 만들어서 따로 떼어낼 수 있을 것 같다.



def is_admin(user_name):
     if user_name != 'admin':
          raise Exception("권한이 없다니까요 ")

class greet(object):
     current_user = None
     def set_name(self,name):
         is_admin(name)
         self.current_user = name

     def get_greeting(self,name):
         is_admin(name)
         return "Hello {}".format(self.current_user)

greet = greet()
greet.set_name('admin')
print(greet.get_greeting('admin') )
문제169. 이름을 넣어서 함수를 실행하면 해당 사원의 월급이 출력되게 함수를 생성하는데
     KING 만 월급을 볼 수 있게 하고 KING이 아닌 다른 사원들은 권한이 없다면서 볼 수 없게 에러가 나게 하시오 !

import pandas as pd
def is_admin(user_name):
     if user_name != 'KING' and :
          raise Exception("권한이 없다니까요 ")

class find_sal(object):
     current_user = None
     def set_name(self,name):
         is_admin(name)
         self.current_user = name

     def get_sal(self,name):
         is_admin(name)
         emp = pd.DataFrame.from_csv("d:/data/emp.csv")
         sal= emp[['sal']][emp['ename'] == name].values[0][0]
         return sal

find_sal  = find_sal ()
find_sal.set_name('KING')
print(find_sal.get_sal('KING') )

문제170.위에 is_admin(name) 이라는 함수를 사용해서 코드가 더 좋아졌다 하지만 데코레이터를 이용하면 함수가 더 
     좋아진다. 데코레이터를 써서 구현하시오 

def is_admin(func):
  def wrapper(*arg,**kwargs): # *arg 리스트의 가변 매개변수
                              # **kwargs 딕셔너리 가변 매개변수
    if kwargs.get('name') != 'admin':
        raise Exception("권한이 없다니까요 ")
    return func(*arg,**kwargs)
  return wrapper

class greet(object):
     current_user = None
     @is_admin
     def set_name(self,name):
         self.current_user = name

     @is_admin
     def get_greeting(self,name):
         return "Hello {}".format(self.current_user)

greet = greet()
greet.set_name(name='admin')
print(greet.get_greeting(name='admin') )

문제171. 문제169 코드를 데코레이터 함수를 이용해서 더 좋게 개선시키시오



import pandas as pd
def is_admin(func ):
  def wrapper(*arg,**kwargs): # *arg 리스트의 가변 매개변수
                              # **kwargs 딕셔너리 가변 매개변수
    if kwargs.get('name') != 'KING' :
        raise Exception("권한이 없다니까요 ")
    return func(*arg,**kwargs)
    if arg[1] == 'SCOTT' :
        raise Exception("스콧이당!")
    return func(*arg,**kwargs)
  return wrapper

class find_sal(object):
     current_user = None
     @is_admin
     def set_name(self,name):
         self.current_user = name

     def get_sal(self,name):
         emp = pd.DataFrame.from_csv("d:/data/emp.csv")
         sal= emp[['sal']][emp['ename'] == name].values[0][0]
         return sal

find_sal  = find_sal ()
find_sal.set_name(name = 'KING')
print(find_sal.get_sal(name = 'KING') )



import pandas as pd
def is_admin(func ):
  def wrapper(*arg,**kwargs): # *arg 리스트의 가변 매개변수
                              # **kwargs 딕셔너리 가변 매개변수
    if arg[1] == 'SCOTT' :
        raise Exception("스콧이당!")
    return func(*arg,**kwargs)
    if kwargs.get('name') != 'KING' :
        raise Exception("권한이 없다니까요 ")
    return func(*arg,**kwargs)
  return wrapper

class find_sal(object):
     current_user = None
     @is_admin
     def set_name(self,name):
         self.current_user = name

     @is_admin
     def get_sal(self,name):
         emp = pd.DataFrame.from_csv("d:/data/emp.csv")
         sal= emp[['sal']][emp['ename'] == name].values[0][0]
         return sal
find_sal  = find_sal ()
find_sal.set_name(name = 'KING')
print(find_sal.get_sal('SCOTT') )


객체와 클래스 (가장 중요한 단원) 


■ 어제 배운내용 복습
1. 클래스 멤버 2가지
                    -- public member
                    -- private member
2. 상속
     - 상속이 필요한 이유? 코드를 간결하게 하기위해서
       객체 지향언어를 제대로 활용하는 방법(object -oriented )
          1팀 : 로폿팔 클래스
          2팀 : 로봇다리 클래스
          3팀 : 로봇 몸체 클래스
          4팀 : 로봇 두뇌(인공신경망) 클래스 
          로봇팔에 버그가 있어 개선하는데 다리까지 영향을 끼친다 안돼!
          ==> 결국 유지보수 비용을 줄일수 있다.
          파이썬 (코어) 개발
          파이썬 개발자 중급 400 ~ 600 

  • 객체 (인스턴스)? 리스트 , 튜플, 딕셔너리 처럼 데이터를 다루기 위한 논리적 집합
                              ↓                                 ↓
                데이터를 어떤 형식으로 저장할 건가?    속성(변수)에 데이터를 넣고     
                                                   기능(함수)로 데이터를 다루는 역할


3만건의 영어 단어장 ----- 겨울왕국 스크립트 리스트 --->
       리스트                리스트                  full table scan 
                                                    (100초)

       딕셔너리              딕셔너리                index scan
       key:value            key:value               (1초)

  • 클래스란? 변수 + 기능 으로 구성된 논리적 집합 ! 
     인스턴스? 클래스(설계도) 를 실체화 한것

문제172. gun이라는 인스턴스를 생성하기 위해서 gun() 클래스를 생성하시오
     gun = gun()    # 총 설계도로 총을 실체화 시킴
     gun.charge(10) # 총알 10발 충전
     gun.shoot(3) 
       탕
       탕
       탕 
     7발 남았습니다. 

     gun.print() # 현재 총알이 얼마나 남았습니다. 
     7발 남았습니다. 

class gun:
    def __init__(self):
        self.bu =0
    def print(self):
        print('{} 발 남았습니다.'.format(self.bu))

    def charge(self,n):
        self.bu += n

    def shoot(self,a):
        for i in range(a):
            if self.bu > 0 :
                self.bu -= 1
                print ('탕 !')
            elif self.bu == 0 :
                print('총알이 없습니다')
                break

        print(self) 

gun = gun()    # 총 설계도로 총을 실체화 시킴
gun.charge(10) # 총알 10발 충전
gun.shoot(4)
gun.print()

예제2. 클래스를 사용하는 이유? 

class employee(object) 
  pass

emp_1 = employee()
emp_2 = employee()

예제2. 클래스를 사용하는 이유?

- 딕셔너리를 사용하는 경우

student = {'name': '김인호', 'year':2,'class':3,'student_id':35}

print('{}, {}학년 {}반 {}번'.format(student['name'],student['year'],student['class'],student['student_id']) )

- 클래스를 사용하는 경우 

class student(object):
     def __init__(self,name,year,class_num,student_id):
          self.name = name
          self.year = year
          self.class_num = class_num
          self.student_id = student_id

     def introduce_myself(self):
          return '{}, {}학년 {}반 {}번'.format(self.name, self.year, self.class_num,self.student_id)

student = student('김인호',2,3,35)

print (student.introduce_myself())


문제173. 위의 student 클래스를 다시 실행하는데 self 빼고해라

TypeError: introduce_myself() takes 0 positional arguments but 1 was given

introduce_myself()라는 메소드는 인자값을 안받게 만들어줘놓고 왜 하나를 줬느냐

인스턴스의 메소드를 호출하면 인스턴스 자기 자신인 self가 첫번째 인자로 자동으로 전달되기 때문이다.

def introduce_ myself():  # <-- self가 없습니다.

파이썬에서는 인스턴스의 메소드를 호출함녀 인스턴스 자기자신인 self가 첫번재 인자로 자동으로 전달되므로 
반드시

def introduce_myself(self)  # <=== self를 넣어줘야 한다. 

문제173. 자기 자신이 인스턴스의 메소드에 인자로 전달된다는 것이 어떤것인지 인스턴스를 통하지 않고
바로 클래스 introduce_myself를 직접 호출해서 확인하시오 

class student(object):
     def __init__(self,name,year,class_num,student_id):
          self.name = name
          self.year = year
          self.class_num = class_num
          self.student_id = student_id

     def static introduce_myself(self):
          return '{}, {}학년 {}반 {}번'.format(self.name, self.year,

self.class_num,self.student_id)

student1 = student('김인호',2,3,35)

print (student.introduce_myself())


■  self 를 왜 강조하느냐?

파이썬은 객체함수를 나타낼때 무조건 def(self,x,y)
이렇게 self를 첫번째 인자로 넣어야한다.
자바나 c++에서는 this 를 명시 안해도 되나 파이썬은 강제입니다.
 
■ static method ?
(정적 메소드 ) 

 - self를 매개변수로 받지 않는 메소드
 - 여러 인스터스가 공유해서 사용하는 메소드

  

class gun:
    def __init__(self):
        self.bu =0
    def print(self):
        print('{} 발 남았습니다.'.format(self.bu))

    def charge(self,n):
        self.bu += n

    def shoot(self,a):
        for i in range(a):
            if self.bu > 0 :
                self.bu -= 1
                print ('탕 !')
            elif self.bu == 0 :
                print('총알이 없습니다')
                break

        print(self) 

gun1 = gun()   
gun1.charge(10)
gun1.shoot(4)
gun1.print()

gun2 = gun()   
gun2.charge(10)
gun2.shoot(4)
gun2.print()

설명: gun1 총과 gun2총은 서로 다른 총입니다.
     같은 설계도를 사용했지만 별개의 총이다.
     별개의 총이 맞는지 확인해본다.
print(gun1)
print(gun2)
<__main__.gun object at 0x000000000C497828>
<__main__.gun object at 0x000000000C525D30>

print(gun1.__class__)
print(gun2.__class__)
<class '__main__.gun'>
<class '__main__.gun'>
 
 둘은 다른 메모리 주소값을 가지고 있어서 
같은 클래스를 쓰는 서로 별개의 오브젝트라는 것을 확인함

문제174. gun class 의 메소드들을 static method들로 변경해서 다시 총을 쏘시오 


class gun:

    bu = 0
    @staticmethod
    def charge(n):
        gun.bu += n

    @staticmethod
    def shoot(a):
        for i in range(a):
            if gun.bu > 0 :
                gun.bu -= 1
                print ('탕 !')
            elif gun.bu == 0 :
                print('총알이 없습니다')
                break

    @staticmethod
    def print():
        print('{} 발 남았습니다.'.format(gun.bu))

gun1 = gun()
gun1.charge(10)
gun1.shoot(3)
gun1.print()

gun2 = gun()
gun2.shoot(7)
gun2.print()
결과 :
탕 !
탕 !
탕 !
7 발 남았습니다.
탕 !
탕 !
탕 !
탕 !
탕 !
탕 !
탕 !
0 발 남았습니다.

문제175. static method로 선언한 클래스를 이용해서 인스턴스화한 두개의 총의 쏘는 메소드(shoot) 이 서로 같은 메모리를 쓰는지 다른 메모리를 쓰는지 확인하시오 


  • 9장 목차
  1. 객체와 클래스
  2. 클래스의 정의
  3. __init__() 메소드를 이용한 초기화작ㅇ업
  4. self에 대한 이해 
  5. 정적 메소드와 클래스 메소드 
  6. 클래스 내부에게만 ㅇ려려있는 프라이빗 멤버
  7. 상속
  8. 오버라이딩
  9. __call()__ 메소드 
  10. for문으로 순회를 할 히 있는 객체 만들기 
  11. 추상기반 클래스 


■9.10 마법의 __call__ 메소드

예제:
class sample(object):
     def __init__(self):
          print("전 생성하면 바로 생성이 돼요")

sample = sample()

설명: __init__ 메소드는 인스턴스를 생성하면 바로 실행이 된ㄷ.

예제2 :
class sampel2(object):
     def __call__(self):
          print("인스턴스에 괄호를 붙이면 제가 실행돼요")

sample2 = sample2()
sample()

클래스의 인스턴스를 함수처럼 호출하기 위해서 
클래스의 __call__ 이란느 매직 메소드를 정의했다
이 원리를 이용해서 클래스를 데코레이터로 구현할 수 있다
어제 우리가 데코레이터로 구현한건 클래스가 아니라 함수였다.

■ 클래스를 데코레이터로 구현하는 예제

from functools import wraps

class onlyadmin(obejct):               # 함수에 들어가는 매개변수의 문자열을 받아서
     def __init__(self,func):          # 대문자로 변환해줌
          self.func= func

     def __call__(self,*args,**kwargs):
          name = kwargs.get('name').upper()
          self.func(name)

def greet(name):
     print("Hello {}".format(name) )

greet(name = 'Scott')
결과 : Hello Scott

문제176. 위의 onlyadmin 데코레이터를 활용해서 find_job이라는 함수를 강력하게 하시오 ! 
find_job(name= 'scott')

당신의 직업은 ANALYST 입니다.



from functools import wraps
import pandas as pd

class OnlyAdmin(object):
    def __init__(self, func):  # 대문자로 변환해주며 함수를 실행해주는 클래스
        self.func = func

    def __call__(self, *args, **kwargs):
        name = kwargs.get('name').upper()
        return self.func(name)

@OnlyAdmin
def find_job(name):

    emp = pd.DataFrame.from_csv('d:/data/emp.csv')

    job = emp[['job']][emp['ename'] == name].values[0][0]
    return job


find_job(name='SCOTT')



  • 9장 목차
  1. 객체와 클래스
  2. 클래스의 정의
  3. __init__() 메소드를 이용한 초기화작ㅇ업
  4. self에 대한 이해 
  5. 정적 메소드와 클래스 메소드 
  6. 클래스 내부에게만 ㅇ려려있는 프라이빗 멤버
  7. 상속
  8. 오버라이딩
  9. __call()__ 메소드 
  10. for문으로 순회를 할 히 있는 객체 만들기 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  11. 추상기반 클래스 

■ 9.11 for 문으로 순회를 할 수 잇는 객체 만들기

Iterator 는 next() 메소드로 데이터를 순차적으로 호출하는 object이다. 

예제 :
for i in range(5) :
     print(i) 

우리가 당연하게 사용했던 위와 같은 for 문은 사실 range() 로 생성된 list 가 iterable 하기 때문에 순차적으로
member 들을 불러서 사용이 가능했던 것이다.

x = [1,2,3]
next(x)


■ 9.12 추상 기반 클래스 

상속일나 클래스의 재사용을 높임으로써
  1. 코드의 반복을 줄이고
  2. 유지보수 비용을 낮추는데 큰 역할을 한다

이러한 상속과 함께 객체지향(object-oriendted) 프로그램의 가장 중요한 특징중 하나가 다형성이다

다형성이란 클래스에 선언된 메서드가 상속 받은 클래스에서 같은 이름으로 
오버라이딩 되어 여러 형태로 동작함을 의미한다. 
예 :                동물 

               메소드 : 짓는다 (비어있는 메소드)
               ↙                        ↘
          고양이                         개

     짖는다 메소드 : 야옹               짖는다 메소드 : 멍멍 



                    동물   <--- 아직 덜 구체화된 상태 --> 그래서 객체화 시키기에는
                ↙          ↘
               고양이        개 <---- 구체화 된 상태

동물 넌 너무 추상적이야 그러니 너는 객체를 만들지마
!

그래서 추상 클래는 상속을 위해서 필요하긴 하지만 개체화해서는 안되는 클래스

추상 클래스는 추상 메소드가 있는 클래스를 말한다
추상 메소드는 바디(내용)가 없는 메소드이다.

추상 클래스를 상속 받는 자식 클래스에서 반드시 지켜줘야 할 사항은 ?

추상 클래스내에는 추상 메소드와 일반 메소드들이 있을 텐데 
그중에 추상 메소드는 반드시 가져와서 오버라이드 해야한다.

예제: 

from abc import ABCMeta, abstractmethod # 파이썬은 추상 클래스를 제공하지 않아서 import받아야한다.


class animal(object):

__metaclss__ = ABCMeta # 추상 클래스로 선언
@abstractmethod # 추상 메소드 선언
def bark(self):
     pass # 비어있는 메소드, 상속받는 자식들이 반드시 구현해야 하는 중요한 메서드

class cat(animal):

def __init__(self):
     self.sound = '야옹'


def bark(self):
     return self.sound


class dog (animal) :

def __init__(self):
     self.sound = '멍멍'
def bark(self) :
     return self.sound

cat = cat()

dog = dog()


print(cat.bark())

print(dog.bark())




문제177. 음료(beverage) 라는 추상클래스 생성하고
          아메리카노(americano)와 카페라떼 (caffelatte) 클래스를
          자식 클래스로 생성하시오 
          
          추상 클래스를  통해서 반드시 구현해야 하는 데메소드는 음료 가격임 












'PYTHON' 카테고리의 다른 글

English stopword , 영어 불용어  (0) 2018.09.18
gcp를 이용해서 jupyter notebook / jupyter lab 서버 만들기  (0) 2018.08.27
8장. 모듈  (0) 2017.09.10
7장. 함수  (0) 2017.09.10
6장. if 문과 loop문 (p126)  (0) 2017.09.10

8장. 모듈

PYTHON2017. 9. 10. 00:43
8장 모듈
- 모듈이란?
- import 사용법
- 모듈 찾는방법
■8장 목차

  1. 모듈이란. ?          : 함수 생성한 것들을 모아놓은 스크립트
  2. import사용법         : 다른 모듈내의 코드에 접근 가능하게 하는 명령어
  3. 모듈찾는방법         : sys.path의 내용을 출력해서 파이썬이 어떻게 모듈을 탐색해 나가는지 확인
  4. 메인모듈과 하위모듈  : 오늘 부터 !배울 내용
  5. 패키지
  6. __init__.py
  7. site - package

■ 8.4 메인 모듈과 하위 모듈 (p 171) 

               파이썬 문법 + 중요한 알고리즘 20가지는 외워버려야 한다.

  1. 코드를 어떻게 만드느냐? 함수 생성, 함수 생성을 한 것을 모아 놓은 모듈
  2. 코드를 어떻게 실행하느냐 ? 메인 모듈 ( 최상위 수준으로 실행되는 스크립트 ) 
                                             예 : 실뭉치의 끝

  • _name_ (내장 전역변수) 를 이용하면 지금 쓰고있느 모듈이 메인 모듈인지 하위 모듈인지 확인할 수 있다.

     메인 모듈: _name_ ---> main 이라고 나오고
     하위 모듈: _name_ ---> 모듈명으로 나온다

예제 : top_level.py 란느 이름으로 저장하고 실행

print('name : {0} '.format(__name__) )

결과 : name : __name__

예제2: sub.py 라는 이름으로저장하고 실행
print("beginning of sub.py...")
print('name : {0}'.format(__name__) ) 
print("end of sub.py...")

먼저 실행하면 결과가 어떻게 나오는가 ?


■ 8.5 패키지 
패키지란 ? 모듈을 모아놓은 디렉토리를 말한다 ( 모듈 꾸러미)

모듈일나? 실행할 함수들을 모아놓은 스크립트

글너데 평범한 디렉토리가 파이썬의 패키ㅣㅈ로 인정 바등려며 ㄴ

__ini__.py 라는 파일이 그 디렉토리 안에 있어야 한다. 

예 : d\python <--- 퍀키지로 인정을 받으려면 ?

__init__.py   <------- 비어있는 문서
calculator.py   <------ 모듈


■ 8.6 _ini_.py 에 대해 (p 175) 

_init_.py 는 보통 비워둡니다 . 이 파일을 손대는 경우는 __all__ 이라는 변수를 조정할 때이다.

__all__ 변수? 패키지로 부터 반입할 모듈의 목록을 정의하기 위해 사용한다

즉 어제 from  패키지 import * 라고 했는데 

이 * 가 패키지 내에 모든 모듈들을 반입하겠다 라는 뜻인데

그 모든 모듈들이 뭐가 있는지 파이썬이 알려며 _ini_.py에 __all__ 변수에 
아래와 같이 명시를 해줘야 한다. 

예: __all__ =['plus_module','minus_module','multiply_modue','divide_module']

  • 실습 : 
  1. d:\python 폴더 아래에 4개의 모듈을 만들어서 저장한다. 
-- plus_module.py로 아래의 스크립트를 저장 


def plus(a,b):
     return a+b

-- minus_module.py로 아래의 스크립트를 저장

def minus(a,b):
     return a-b

-- multiply_module.py로 아래의 스크립트를 저장

def multiply(a,b):
     return a*b

  1. d:\python 폴더 아래에 _ini_.py에 아래의 내용을 저장
__all__ =['plus_module','minus_module','multiply_moduㅣe']
  1. d:\python 폴더의 상위 디렉토리에 cal_test.py라는 이름으로 아래의 스크립트를 저장하고 실행

from python import *

print ( calculator.plus(10,5))
print ( calculator.minus(10,5))


■8.7 site - package 에 대해서 

 site - package 란 파있너 기본 라이브러리 패키지외에 추가적인 패키지를 설치하는 디렉토리이다.

 site - package 디렉토리에 여러가지 소프트웨어가 사용할 공통 모듈을 넣어두면 ㅁ루리적안장소에 구애받지 않고 모듈에  접근하여 반입할 수 있다.

import sys

sys.path
C:\ProgramData\Anaconda30\Lib\site-packages
문제 163. d:\my_loc2라는 디렉토리를 만들고 cal_test.Py 스크립트를 가져다 두고 실행해보세요 

'PYTHON' 카테고리의 다른 글

gcp를 이용해서 jupyter notebook / jupyter lab 서버 만들기  (0) 2018.08.27
9장. 객체와 클래스 (가장 중요한 단원)  (0) 2017.09.10
7장. 함수  (0) 2017.09.10
6장. if 문과 loop문 (p126)  (0) 2017.09.10
1-5장  (0) 2017.09.10

7장. 함수

PYTHON2017. 9. 10. 00:42
■ 7장. 함수 

  • 7장. 목차 
  • 1.함수생성하는 방법
  • 2.기본값 매개변수와 키워드 매개변수 (mit 코드 이해)
  • 3.가변 매개변수  (mit 코드 이해)
  • 4.매개 변수로 함수를 사용하는 경우
  • 5.함수 밖의 변수, 함수 안의 변수
  • 6.재귀함수  (mit 코드 이해)
  • 7.중첩함수 

■ 7.1. 함수 생성하는 방법

def 함수일므 (매개변수):

     실행문
      return 결과


예제: def my_abs(arg):
       if (arg < 0 ) :
          result = arg * -1 
       else:
          result = arg
       return result
      print ( my_abs(-5) )

문제146. 아래와 같이 이름을 입력하새 함수를 실행하면 
          해당 사원의 부서위치가 출력되게하시오!

print( find_loc('SMITH') )

def find_loc(name)
 for e in emp:
  for d in dept:
   if e['deptno'] == d['deptno'] :
      if e['ename']  == name :
          print( e['ename'].ljust(7),d['loc'])

find_loc('SMITH')

import pandas as pd
def find_loc(val):
    emp= pd.read_csv("D:\data\emp.csv")
    dept= pd.read_csv("D:\data\dept.csv")
    result  = pd.merge(emp,dept,on='deptno')
    result2 = result[['loc']][result['ename']== val]

    return result2
문제147. 미분계수를 구하는 함수를 생성하는데 
 함수 f(x) = 2x^2 +1 일때 

def mibun_fun(n):
 return 'x가 '+ str(n) +'에서의 기울기는 '+ str(round((2*(n + 0.00000001)
*(n + 0.00000001)+1 - (2* n*n+1) ) / 0.00000001)) + ' 입니다.'
print(mibun_fun(-2))


■ 매개변수로 함수를 받는 경우 


def numerical_diff(f,x):
    delta = 0.0001 # 1e-4로 해도된다
    return ( f(x+delta) - f(x-delta) ) / (2*delta)
함수  f(x) 2x^2 + 1 생성

def function_1 (x) :
     return 2*pow(x,2) +1

print( numerical_diff(function_1,-2) )


문제148. 함수 f(x) = x^2 -x +5 함수의 x가 -2일때 미분계수를 구하시오 





■ 지난 주에 배웠던 내용 복습
  1. 함수
- 머신 러닝을 이해하기위한 Mit TTT 코드 구현
- 웹 스크롤링 ----> 빅데이터 수집
  1.  
6장함수 
for 
while
continue
break

5장. 파이썬 자료형 3가지 
  1. 리스트 []
  2. 튜플 ()
  3. 딕셔너리 {} (키와 값으로 구성된 자
   - 어순 번역기
   - nested loop join 구현
          ↓ data 양이 많아지면 느려진다.
   - hash join 으로 구현 (해쉬 알고리즘)  오라클이 이걸로 다른rdb회사 눌러버림

  1. Pandas 모듈을 이용해서 데이터 검색
          판다스 데이터 프레임 [ 열 ] [ 행 ]
            ↓  <---- 그룹함수 구현
           판다스 데이터 프레임 [ 열 ] [ 행 ] .max()
                                              .sum()
                                              .min()
                                              .mean()

           ↓  
          판다스 데이터 프레임.groupby([열])['기준컬럼(sal)'].max()

요번주 : 7장 함수, 8장. 모듈과 패키지 , 9장 .클래스 , 10장. 예외처리  
          11장. 파일에서 데이터 읽고 쓰기 ------> Tic Tac Toe 게임

     1세대 인공지능: 1954년 캠브리지 대학에서 Tic Tac Toe 를 사람과 게임할 수 잇또록 구현
          ↓ 
     체스가 구현 
          ↓ ----> 신경망(딥러닝) 
     오목, 바둑  (2016년)

     인공지능에서 무언가 혁신적인게 나온다면 그것은 바로 구글에서 나올것이다.
      - 에릭 슈미스 (구글 사장 ㅋ)




■ 7장. 함수 

  • 7장. 목차 
  • 1.함수생성하는 방법
  • 2.기본값 매개변수와 키워드 매개변수 (mit 코드 이해)
  • 3.가변 매개변수  (mit 코드 이해)
  • 4.매개 변수로 함수를 사용하는 경우
  • 5.함수 밖의 변수, 함수 안의 변수
  • 6.재귀함수  (mit 코드 이해)
  • 7.중첩함수 

■ 7.2. 기본값 매개변수와 키워드 매개변수 (p 145)
기본값 매개변수? 입력하지 않으면 기본으로 할당되는 매개변수

예 : log(4   ,   2)    ,    log(10)
         ↑      ↑              ↑
       지수     밑수             지수    밑수는 자연상수e 가된다.

예제 : 
 def print_string(text,count = 1): #  count = 1 디폴드 값을 지정
  for i in range(count):
    print(text)
 
 print(print_string("안녕하세요") )
 print(print_string("안녕하세요"),3 )

문제149. 아래와 같이 이름만 넣으면 소속팀과 직위가 출력되는 함수를 생성하시오 
def print_string(name='장경원',team='머신러닝팀',position='팀장'):
  print(name)
  print(team)
  print(position)

 
def print_string(name,team='머신러닝팀',position='팀장'):
  print('이름 = {0}'.format(name) )
  print('소속팀 = {0}'.format(team ) )
  print('직위 = {0}'.format(position ) )

설명 : 문자열.format()

■ Mit TTT코드에서 기본값 매개변수 사용하는 부분 

class Agent(object):

    def __init__(self, player, verbose = False, lossval = 0, learning = True):

        self.values = {}

        self.player = player

        self.verbose = verbose

        self.lossval = lossval

        self.learning = learning

        self.epsilon = 0.1

        self.alpha = 0.99

        self.prevstate = None

        self.prevscore = 0

        self.count = 0

        enumstates(emptystate(), 0, self)

■ 가변 매개변수 (p147) 
문자열.format() 함수 처럼 매개변수의 수가 유동적인 함수를 만들고 싶을 때 사용하는 변수 
함수 실행할때 매개변수를 10개 , 20개를 입력해도 제대로 동작을 한다. 

예 :
def 함수이름(*매개변수):
          코드 블럭

예제:
def merge_string(*text_list):
     result = ''
     for s in text_list:
      result = result + s + '  '
     return result
merge_string('아버지가','방에','들어가신다')  

파이썬에서 * 가 쓰이는 경우 
  1.가변 매개 변수
  2.리스트 변수내의 요소들을 뽑아낼ㄸ ㅐ--> mit 코드


문제150. mit TTT코드에서 보드판을 출력하는 printboard 함수를 분석하시오
(리스트 변수내의 요소를 ㅃ보아내는 문법이 나온다.

# States as integer : manual coding
EMPTY = 0
PLAYER_X = 1
PLAYER_O = 2
DRAW = 3

BOARD_FORMAT = """----------------------------
| {0} | {1} | {2} |
|--------------------------|
| {3} | {4} | {5} |
|--------------------------|
| {6} | {7} | {8} |
----------------------------"""
NAMES = [' ', 'X', 'O']

def printboard(state):
    """ Print the board from the internal state."""
    cells = []
    for i in range(3):
        for j in range(3):
            cells.append(NAMES[state[i][j]].center(6))
    print(BOARD_FORMAT.format(*cells))


printboard([[1,2,0],[0,0,0],[0,0,0]])

print(BOARD_FORMAT.format('a','b','c','d','e','f','g','h','g'))  

print(BOARD_FORMAT.format('x','o','x','o','x',' ',' ',' ',' '))

print(BOARD_FORMAT.format('x'.center(6),'o','x','o','x',' ',' ',' ',' '))


7.4.매개 변수로 함수를 사용하는 경우

  • 함수의 종료의 의미로  return 을 사용하는 경우
예제:
def stop_fun(num) :
  for i in range(1, num + 1) :
    print ('숫자 {0} 울 출력합니다'.format(i)) 
    if i =0 5:
     return 
stop_fun(10)



def enumstates(state, idx, agent):
    if idx > 8:
        player = last_to_act(state)
        if player == agent.player:
            agent.add(state)
    else:
        winner = gameover(state)
        if winner != EMPTY:
            return
        i = int(idx / 3)
        j = idx % 3
        for val in range(3):

               state[i][j] = val
               enumstates(state, idx+1, agent)

문제151. (점심시간 문제) 아래와 같이 숫자를 입력하고 함수를 실행하면 숫자가 세로로 출력되게 하시오 

def print_something(*num):

     for s in num :
         print(s)

  1. 함수 밖의 변수, 함수 안의 변수

     로컬 변수? 함수 내에서만 사용하는 변수
     글로벌 변수? 함수 내,외 둘다 사용 가능한 변수 
               특정함수에서 출력된 결과를 다른 함수에서 사용할 때 
               사용합니다. 


함수안의 변수와 함수 밖의 변수가 서로 이름이 같다해도 전혀 다른 변수이다. 
만약 같은 변수로 취급하려면 global 변수로 선언해야한다. 

예제: 
def scope_test():
  a = 1  # 함수 내에서 사용하는 변수 (로컬변수)
  print ('a : {0}'.format(a) )

scope_test()


문제152. 마지막 위의 스크립트에서 마지막 scope_test()를 실행했을때 a가 1 이 아니라 0이 출력이 되려면
         scope_test() 함수를 생성할 때 어떻게 생성해야 했을가요?
a = 0
def scope_test():
  a = 1  # 함수 내에서 사용하는 변수 (로컬변수)
  print ('a : {0}'.format(a) )

scope_test()

  • 재귀함수
  • 스택구조 
  • 큐구조 : 선입선출( 먼저 들어온게 먼저 처리)

sql에서 큐를 경험해봤다
Enqueuue 락 
서로 업데이트 하려면 락이걸린다. 
a b c 
a: lock holder
b,c : lock waiter 

scott A

update emp
 set sal = 0 
 where ename = 'KING';

* 스택 구조 : 먼저들어간 데이터가 가장 마지마겡 나오는 구조 LIFO
후입 선출 

스택 루프 반복문 
반복문 (LOOP) + 스택 구조 ===> 재귀 알고리즘 

예 : 
def some_func(count) :
  if count > 0 :
     some_func(count -1) 
  print (count)

some_func(100)

10 ---> call하고 기다림 ---> 기다림이 끝나면 print 10
 9 ---> call하고 기다림 ---> 기다림이 끝나면 print 9
 8 ---> call하고 기다림 ---> 기다림이 끝나면 print 8
 7 ---> call하고 기다림 ---> 기다림이 끝나면 print 7
                         :
                         :
                                             print 0 
0 ---> 함수 호출 끝 


문제153. 10! 을 재귀함수로 구현해서 출력하시오 !

def factorial2(count) :

  if count > 0 :
     return count * factorial2 (count -1)
  elif count == 0:
     return 1

문제154. 16과 28의 최대공약수를 출력하는데 재귀함수를 이용해서 
          구현하시오 ! 
find_gcd(20,16)
최대 공약수는 4

find_gcd(108,72) 
최대 공약수는36

def find_gcd(num1, num2):
 if num1%num2 != 0: return find_gcd(num2, num1%num2)               
 else : return num2


li=[]
def find(*num):
if a%b != 0: return find_gcd(b, a%b)               
 elif a%b == 0 : return find_gcd(c, b%c)  
 return c
li=[]
def print_something(*num):





문제155. 오늘 오전에 배운 가변 매개변수와 재귀 알고리즘을 이용해서 최대 
          공약수를 출력하는 함수를 생성하시오 

def find_gcd(a,b,c):
 if a%b != 0: return find_gcd(b, a%b,c)
 elif b%c != 0: return find_gcd(a, b ,b%c)
 return b

def find_gcd(a,b,c):
 if a%b != 0: return find_gcd(b, a%b)               
 elif a%b == 0 : return find_gcd(c, b%c)  
 return c
li=[]
def print_something(*num):

     for s in num :
       li.append(s)

a= 1000%700%74
print (a)


내일 PL/SQL 알고리즘 문제 시험범위: 오픈북, 실습가능

오늘 배운 재귀 알고리즘을 PL/SQL로 구현하는 문제 2개
예 SQL> exec dbms_output.put_line( factorial(5) )



7.7 중첩함수 ( p 158)
" 파이썬에서는 함수 안에 함수를 정의하는거싱 가능하다"
중첩함수는 자신이 소속된 함수의 매개변수에 접근할 수 있다는 특징이 있다. 

예제: p159 쪽 (표준편차를 출력하는 함수)

* 표준편차를 구현하기 위한 함수 2개

   1. 평균값 구하는 함수
   2. 분산을 구하는 함수
   3. 구해진 분산값에 루트를 씌운 값을 출력하는 함수

예제:

(pg159)

import math
def stddev(*args):
    def mean():                               #평균 구하는 함수
        return sum(args)/len(args)

    def variance(m):                       # 분산을 구하는 함수
        total = 0
        for arg in args:
            total += (arg - m) **2
        return total/(len(args)-1)
    v= variance(mean())                # 분산을 구함
    return math.sqrt(v)                 # 분산에 루트를 씌워서 표준편차를 구함

stddev(2.3,1.7,1.4,0.7,1.9)


import math
def stddev(*args):
 def mean():
    return sum(args)/len(args)

 def variance(m):
   total = 0
   for arg in args:
      total += (arg -m) **2
   return total / (len(args)) - 1
v= variance(mean() )
return math .sqrt(v)
stddev(2.3, 1.7, 1.4, 0.7, 1.9)

  
문제156. 가변 매개변수를 이용해서 여러개의 숫자를 입력 받아 최대공약수를 
출력을 해낸 준호의 코드를 가져다가 중첪함수를 구성하시오 ! 

def gcdtwo(a,b):                    두 수의 최대공약수를 출력
                                    분모가 0일경우 에러가 발생하므로 0인 경우를 따로 생각
    if min(a,b) == 0:               # 0 A의 최대공약수는 무조건 A 이기 떄문에
        return max(a,b)             두 수중 최소값이 0인경우 두 수중 맥스값으로 최대공약수 출력
    return gcdtwo(b,a%b)            # 0이 아닌경우에 대해 유클리드호제법으로 재귀

def gcd(a):                         여러 수 중에서 최대공약수를 출력하는 알고리즘
    b=gcdtwo(max(a),min(a))         여러 수 중 두수를 뽑아서 최대공약수를 구하고
                                    다른 두수를 뽑아서 최대공약수를 구하고를 반복해서
    a.remove(min(a))                마지막에 남는 최대공약수가 전체의 최대공약수인 점을 이용
    a.remove(max(a))                정렬할 필요가 없게 전체 수에서 최대최소값을 뽑아서
                                    최대공약수를 구하는데 계산에 사용한 수는 제거하고
    a.append(b)                     위에서 구한 최대공약수를 리스트에 추가
    if max(a)==min(a):              위 과정을 재귀를 통해 반복하면 최대공약수만 2개 남는데
        print('최대공약수는 : ',a[0])  그경우에서 재귀를 종료하고 최대공약수를 출력
    else:
        gcd(a)


def list(*n):                       가변 매개변수로 데이터를 여러개 입력받으면
                                    튜플 형태이기 때문에 데이터 변경이 불가능
    a = []                          리스트를 생성하고 데이터 변경이 가능하도록
    for in n:                     튜플 데이터를 잘라서 리스트에 입력
        a.append(i)
    gcd(a)                          최종적으로 생성한 리스트 변수를
                                    위에 생성한 최대공약수 함수에 입력해서 최대공약수 계산




def list(*n):
    def gcdtwo(a,b):

        if min(a,b) == 0:
            return max(a,b)
        return gcdtwo(b,a%b)

    def gcd(a):
        b=gcdtwo(max(a),min(a))

        a.remove(min(a))
        a.remove(max(a))

        a.append(b)
        if max(a)==min(a):
            print('최대공약수는 : ',a[0])
        else:
            gcd(a)

    a = []
    for i in n:
        a.append(i)
    gcd(a)

list(4,8,12)
list(6842,176,154)

■ 재귀 알고리즘을 완성하는 문제
 MIT 코드를 이해하기 위해서 반드시 알아야하는 알고리즘 
  1. greedy (탐욕) 알고리즘
     당장 눈 앞의 이익만 추구하는 것 
     먼 미래를 내다 보지 않고 지금 당장의 최선이 무언인가만 판단 
 
     예 : 틱택토 코드가 가장 유명한 예이다.


문제157. 탐욕 알고리즘을 이용하여 금액과 화폐가 주어졌을 때 
          가장 적은 화폐로 지불 하시오 !
액수입력 : 362
화폐 단위를 입력 !: 1 50 100

결과 :
100원     3개
50원       1개
1원          12개 




def coinGreedy(money, cash_type):
    cash_type.sort(reverse=True)

    def coinGreedyRecursive(money, cash_type, res, idx):
        if idx >= len(cash_type): #화폐 다 사용 시 종료
            return res

        dvmd = divmod(money,cash_type[idx] )
        res[cash_type[idx]] = dvmd[0]
        return coinGreedyRecursive(dvmd[1] ,cash_type,res,idx+1)

    return coinGreedyRecursive(money,cash_type,{},0)
money = int(input('액수입력 : '))
cash_type = [int(x) for x in input('화폐단위를 입력하세요 : ').split(' ')]
res = coinGreedy(money,cash_type)
for key in res:
    print('{0}원 : {1}개'.format(key,res[key]))



■8장. 모듈과 패키지 
  • 8장 목차 
    • 1. 모듈이란?
    • 2. import 사용법
    • 모듈 찾는 방법
    • 메인 모듈과 하위 모듈
    • 패키지
    • _init_.py

8.1 모듈이란? 독자적인 기능을 갖는 구성요소
              파이썬에서는 각각의 소스파일을 일컬어 모듈이라고 한다. 

모듈 생성 예 :

save as calculator.py
def plus(a,b):
  return a+b

def minus(a,b):
  return a-b

def multiply(a,b):
  return a*b

def divide(a,b):
  return a/b

import calculator

print (calculator.plus(10,5))
print (calculator.minus(10,5))
print (calculator.multiply(10,5))
print (calculator.minus(10,5))

■8.2. import 사용법 
import 의 역할은 정확하게는 다른 모듈 내의 코드에 대한 접근을 가능하게 하는 것이다.
import 가 접근 가능하게 하는 코드에는 변수, 함수 , 클래스등이 모두 포함된다.

앞에서 썼던 문법 :
import 모듈명

import calculator 

print ( calculator.plus(10,5) )
               
         ↓
좀더 편하게 코딩 : from 모듈명 import 변수 또는 함수 

                   from calculator import plus
                   from calculator import minus 
                   from calculator import multiply
                   from calculator import divide

               print ( plus(10,5) )

 
                ↓
좀더 편하게 코딩 : from 모듈명 import *
                    print ( plus(10,5) )

p 168  import * 와 같은 코드는 사용하지 않는것이 좋다.

이유?       코드가 복잡해지고 모듈의 수가 많아지면 어떤 모듈에 또는 어떤 함수를 불러오고 있는지 파악하기 힘들다

좀더 편하게 코딩 : import calculator as c
                    print (c.plus(10,5) )



문제159.오전에 만들었던 준호의 최대공약수를 구하는 함수를 모듈화 하시오 !



if _name_=="__main__": 모듈을 불러올때 이문장 이후의 문장은 수행되지 않음
list (1000,3350,150)

문제160. 표준편차를 출력하는 함수를 모듈화 시켜서 다른 실행창에서 아래와 같이 실행되게 하시오!




■8.3. 모듈 찾는 방법

방금 만든 calculator 모듈의 위치는 우리가 직접 지정한 위치에 저장되어있었고
calc_test.py 에서 calculator 모듈을 불러올 수 있었다. 

sys 라는 모듈( 예: random 함수를 포함하고 있는 모듈) 어디에 있는가?
 
파이썬은 import를 만나면 아래와 같은 순서로 모듈 파일을 찾아나선다.
  1. 파이썬 인터프리터 내장 모듈
  2. sys.path 에 정의 되어 있는 디렉토리 

sys 모듈은 파이썬의 내장 모듈이다. 

sys 모듈에 들어있는 함수들이 뭐가 있는지 확인하는 코드 

import sys
print ( sys.builtin_module_names)

문제161. 혜승이가 sys모듈의  random 함수를 이용해서 경이로운 방법으로 구현해낸 원주율 구하는 코드를 실행해보자 























 
 

'PYTHON' 카테고리의 다른 글

gcp를 이용해서 jupyter notebook / jupyter lab 서버 만들기  (0) 2018.08.27
9장. 객체와 클래스 (가장 중요한 단원)  (0) 2017.09.10
8장. 모듈  (0) 2017.09.10
6장. if 문과 loop문 (p126)  (0) 2017.09.10
1-5장  (0) 2017.09.10



■ 6장. if 문과 loop문 (p126)


    * 6장 목차


    1. if문
    2. for loop문
    3. while loop문
    4. 중첩 loop문
    5. continue와 break 사용법


알고리즘 문제들을 파이썬으로 구현 ---> 전날 알고리즘 문제2개 공부
                                       다음날 문제2개 오픈북
                                       문제만 다른것으로 살짝 변경해서 PL/SQL

알고리즘 문제를 해결하는 목적     ---> 파이썬 프로그래밍을 잘하기 위해서 공채시험문제(파이썬)

■ if문 예제 (p126)

if 조건1 :
 실행문

elif 조건2 :              " 조건이 true  이면 실행이되고 조건이 false이면
 실행문                     실행이 안된다. "

elif 조건3 :
 실행문

else:   <----------- 생략가능
 실행문


    * 조건이 false로 평가 되는 경우 (p 118)


    1. False
    2. None
    3. 숫자 0
    4. 비어있는 순서열 : '' , () : 비어있는 튜플  , [] : 비어있는 리스트
    5. 비어있는 딕셔너리 : {}



문제111. 숫자를 물어보게하고 숫자를 입력해서 짝수인지 홀수인지를 출력하는 if 문을 이용한 파이썬
          코드를 작성하시오!

------------
|  if 문  |
------------
a = input('숫자를 입력하세요 ')
if int(a)%2 == 0 :
     print ('짝수입니다')
else:
     print ('홀수 입니다.')


문제112. 위의 if문의 예제로mod 함수를 구현하시오 !
------------
|  if 문   |
------------
     print  (mod(10))
     짝수입니다.

def mod(a):
 res =''
 if int(a)%2 == 0:
  res ='짝수입니다'
 else:
  res ='홀수 입니다.'
 return res

print(mod(10))

문제113. 이름을 물어보게하고 이름을 입력하면 해당 사원이 고소득자인지
          저소득자인지 출력되게 하시오 !

          월급 >= 3000      고소득자 입니다.
          월급 >= 2000      적당합니다.
          월급 < 2000       저소득자입니다.     


import pandas as pd
emp = pd.DataFrame.from_csv("D:\data\emp.csv")
a= input('이름입력')
empresult = emp[ ['sal'] ][emp['ename'] == a]
empresult = empresult.values[0]
print(empresult)
if int(empresult) >=3000 :
    print ('고소득자입니다')

elif int(empresult) >=2000 :
    print ('적당합니다.')
elif int(empresult) <2000 :
    print ('저소득자입니다.')


문제114. 위의 문제를 다시 수행하는데 이름을 소문자로 입력해도 결과가 출력되게 하시오


import pandas as pd
emp = pd.DataFrame.from_csv("D:\data\emp.csv")
a= input('이름입력')
empresult = emp[ ['sal'] ][emp['ename'] == a.upper()]
empresult = empresult.values[0]
print(empresult)
if int(empresult) >=3000 :
    print ('고소득자입니다')

elif int(empresult) >=2000 :
    print ('적당합니다.')
elif int(empresult) <2000 :
    print ('저소득자입니다.')

문제115. (알고리즘 문제 ) 가우스 공식으로 1부터 10까지의 숫자의 합을 출력하시오 !
------------
|  if 문  |
------------
첫번째 수를 입력하시요 ~ 1
마지막 수를 입력하시오 ~ 10

1부터 10의 합은 55입니다.
a  = input('첫번째 수를 입력하세요 ! ')
b  = input('마지막 수를 입력하세요 ! ')

res ('%a 부터 %b 까지 합은 ',%a , %b)

a  = int(input('첫번째 수를 입력하세요 ! '))
b  = int(input('마지막 수를 입력하세요 ! '))
if a < b
res = (b*(b+1)/2) - (a*(a+1)/2)
res= (a+ b) / 2 *(b- a  -1)
print(int(a),' 부터 ',int(b),'까지 합은 ',int(res))
else :
print ('
첫번재 입력한 숫자가
두번째 입력한 숫자보다 큽니다
')


문제116. 위ㅡ이 문제를 다시 수행하는데 아래와 같이 큰 숫자를 먼저입력하면 첫번재 입력한 숫자가
두번째 입력한 숫자보다 큽니다 라는 메세지가 출력되겧 사ㅗㅇ


a  = input('첫번째 수를 입력하세요 ! ')
b  = input('마지막 수를 입력하세요 ! ')

res ('%a 부터 %b 까지 합은 ',%a , %b)

a  = int(input('첫번째 수를 입력하세요 ! '))
b  = int(input('마지막 수를 입력하세요 ! '))
if a < b:
 res = (b*(b+1)/2) - (a*(a+1)/2)
 res= (a+ b) / 2 *(b- a  -1)
 print(int(a),' 부터 ',int(b),'까지 합은 ',int(res))
else :
 print ('첫번재 입력한 숫자가 두번째 입력한 숫자보다 큽니다')

■ 6.2 for loop  문
문법 : for 반복변수 in 순서열:
                         ↑
          실행문       리스트, 튜플, 문자열

예제:
for i in (1,2,3)   # 리스트
       print (i)

for i in ['a','b','c']
 print(i)

for i in 'I am a boy':
     print(i)

for i in range(0,5):
 print(i)

for i in range(5):
 print(i)

for i in range(1,10,2):
 print(i)

문제117. 구구단 2단을 출력하시오!

2 x 1 = 2
for i in range(2,10):
 for j in range(1,10):
 print(i 'x',i,' = ',i*j)
문제118., 별표 출력 !

for i in range(1,12):
 res=''
 for j in range(1,i):
  res+='★'
 print(res)

 for i in range(1,11):
     print('★'*i)

문제119. 별표 출력 반대로!!

 for i in range(10,0,-1):
     print('★'*i)

문제120. 아래와 같이 출력하시오 !

for j in  range(5):
 print(('w'*j).rjust(10))

for i in range(5,0,-1):
 print(('★'*i).rjust(10))

for i in range(5)
 print ((' '*i),('★'*5-i))

for i in range(5,0,-1):
 print ((' '*i),('★'*5-i))

for i in range(10,0,-1):
    if i>=5:
        a=(' '*i)
        b=('★'*(10-i))
        print(a+b)
    elif i<5:
        c=(' '*(10-i))
        d=('★'*(i))
        print(c+d)

문제121. 중첩 for loop 문을 이용해서 ★ 로 사각형을 만드시오 !

가로의 숫자를 입력하시오 5
세로의 숫자를 입력하세요 5

★ ★ ★ ★ ★
★ ★ ★ ★ ★
★ ★ ★ ★ ★
★ ★ ★ ★ ★
★ ★ ★ ★ ★


a = int(input('세로숫자를 입력하세요 '))
b = int(input('가로숫자를 입력하세요 '))

-- for loop 중첩 안 했을 때
for i in range(a):
 print ('★'*b)


-- for loop 중첩 했을 때
for i in range(a):
 res = ''
 for j in range(b):
  res += '★'
 print(res)


문제122. 구구단을 가로로 출력하시오 ~

for i in range(1,10):
 res = ''
 for j in range(2,10):
   res += (str(j)+' x '+str(i)+' = '+str(i*j)+ '  ').ljust(13)
 print(res)

문제123. for loop 문을 이용해서 power함수를 구현하시오
밑수를 입력하세요 ~ 2
지수를 입력하세요 ~ 3

2의 3승은 8 입니다.


a = int(input('밑수를 입력하세요 '))
b = int(input('지수를 입력하세요 '))
res =1
for i in range(b):
    res *= a

print (a,'의 ',b,'승은 ',res,'입니다')

설명:

    1. ('★' for i in ragne(5)) # for loop 문을 5번 돌려서 ★★★★★
    2. join : ★5개를 모아주는 메소드
    3. ''. : result 변수를 '' (None)으로 하겠다.

■ 숫자, 문자, 공백이 스크립트안에 얼마나 포함되었는지 확인하는 방법
 s = 'some stirng'

 numbers = sum(c.isdigit() for i in s)
 words   = sum(c.isalpha() for i in s)
 space = sum(c.isspace() for i in s)

문제124. 겨울왕국 대본에는 숫자가 몇개나 있는가?
numbers =0
text_file = open("d:\data\winter.txt",'r')
lines = text_file.readlines()
total = 0
for i in lines :
  numbers += sum(c.isdigit() for c in i )

문제125. 공백도 아니고 문자도 아니고 숫자도 아닌 문자가 (특수문자)
         몇개 나 있는지 확인하시오
text_file = open("d:\data\winter.txt",'r')
lines = text_file.readlines()
numbers =0
total = 0
alpha = 0
spaces =0
for i in lines :
 total += len(i)
 numbers += sum(c.isdigit() for c in i )
 alpha += sum(c.isalpha() for c in i )
 spaces += sum(c.isspace() for c in i )

print(total-numbers-alpha-spaces)
■while loop
문법 : while 조건 :
          실행문


예제 :
print ('몇번 반복할까요 : ? ')
limit = int(input('반복할 횟수를 입력하세요'))
count = 0
while count < limit:
     count += 1
     print('{12} 회 반복.'.format(count) )

문제126. 숫자를 물어보게하고 숫자를 입력하면 해당 숫자만큼
         아래와 같은 그림이 그려지게 하시오!

숫자를 입력하세요  6

c=0
a = int(input('숫자를 입력하세요  '))
while c < a :
 c+=1
 quf =('★'*c).rjust(10)
 print(quf)
문제127. 팩토리얼 while loop 문으로 구현하시오 !
     팩토리얼 숫자를 입력하세요 !  5
     120 입니다.
     5*4*3*2*1

문제128. log함수를 파이썬으로 구현하시오 ! (while loop문으로 )
          ( 알고리즘 문제 6번)

c= 0
a = int(input('밑수를 입력하세요 '))
b = int(input('지수를 입력하세요 '))
if a%b == 0 :
while a < b :
 c+=1
 a = c * a
-- 정수자리 찾기! 완료








다우니 향!~
노말 퍼퓸

문제129. (공채에서 가장 많이 나온느 알고리즘 문제)
          두수를 입력 받아서 최대공약수를 구하시오 !
          while loop 문 + 유클리드 호제법
     첫번째 수를 입력하세요 ~ 24
     두번재 수를 입력하세요 ~ 18
          6 입니다.


while a%b !=  0 :
 if b > a :
  (a, b) = (b, a) # swap !!!!
 c = a%b
 a = b
 b = c
print (str(c)+'입니다')

-- 정수자리 찾기! 완료



문제130. (마지막 문제) 최대 공약수를 알굇픙ㄴ 2개 숫자를 입력하세요

a = input('최대공약수를 알고 싶은 2개의 숫자를 입력하세요 ')
li = []
li = a.split(' ')
a = int( li[0] )
b = int( li[1] )
while a%b !=  0 :
 if b > a :
  (a, b) = (b, a) # swap !!!!
 c = a%b
 a = b
 b = c
print (c)




■ 6장. if 문과 loop문 
           - for loop
             -알고리즘
               1.금방생각해도 구현할 수 있는 문제
               2.오래 생각해야 구현할 수 있는 문제
               ( 버블정렬, 최단거리, 탐욕 알고리즘 ) 
                                        ↑
                                   mit 공대 코드
               mit 공대 머신러닝 코드를 이해하기 위한 문법?
                    1.format 함수     
                    2.for loop
                    3.함수 생성하는 방법
                    4.자료형 - 리스트, 튜플, 딕셔너리
                    5.if 문
                    6.몬테칼르로 알고리즘  -- 혜승이 원주율 구하는 코드 
                                               파이썬으로 구현 !
                    7.탐욕 알고리즘
                    8.수학공식
               
          self.values[self.prevstate] += self.alpha * (nextval - self.prevscore)
               - while loop

■ 6장. if 문과 loop문 (p126)

  • 6장 목차
  1. if문
  2. for loop문
  3. while loop문
  4. 중첩 loop문


■ 6.4.  continue 문(p137) 

 "반복문이 실행되는 동안 특정 코드블럭은 실행하지 않고
   다른 코드 블럭만 실행되게 할때 사용하는 문법 "

예제 설명: 

 for i in range(10) :
   if i $ 2 == 1:
     continue         # 홀수는 컨티뉴 제껴라!
   print (i)



문제131. 숫자를 1부터 10까지 출력하는데 중간에 5는 나오지 않게 ! 

for i in range(10):
 if i == 5 :
     continue
 print (i)


■ break 문
     "루프를 중단시키는 역할을 하는 문법"

예제 :   



    i  =  0
             while (True) : # 무한 루프 돌리겟따
             i += 1
             if i == 1000:
                 print('i가 {0}이 됨. 반복문을 중단함',format(i))
                 break
             print(i)
문제132. 함수를 생성하는데 아래와 같이 숫자를 넣어서 실행하면 
          해당 숫자만큼 숫자가 세로로 출력되게 하시오 ~
print( break_fun(10) ) # 10 이 loop문을 중단시킬 숫자 
1
2
3
4
5
6
7
8
9
10
none

문제133. 위의 함수를 수정해서 결과가 아래와 같이 가로로 출력되게 하시오 


def break_fun(val):
    res =''
    num =1
    while 1:
        res += str(num) + ' '
        if num == val:
            break
        num += 1

    print(res)
print(break_fun(10))

■6장에서 배운 내용 if 문과 loop[문을 정리하는 문제

  • pandas 를 이용해서 1.판다스 기본 문법

  •     pandas를 이용하지 않고 조인
  • 1. for loop문을 중첩해서 문제를 해결
  • 2. 딕셔너리 데이터 타입을 이해 (mit 코드에서도 중요하게 쓰인다.)

문제134. 아래와 같이 딕셔너리 형태의 데이터를 만들고 출력하시오 !
  • 파이썬 데티ㅓ 구조 3가지 1.리스트 2.튜플 3.딕셔너리(키와 값으로 구성)
emp_dic = {'mgr':'7788','sal':'1100','deptno':'20','comm':'0','job',:'CLERK','hiredate':'1983-01-15','empno':7876','ename':'ADAMS'}

emp_dic
emp_dic['mgr']

문제135. 6장에서 배운 for loop 를 이용해서 emp2.csv를 읽어와서 emp_dict라는 딕셔너리 데이터 유형ㅇ르 만드시오 
import csv
emp_file = open("D:\data\emp.csv",'r')
emp_csv = csv.reader(file)
emp = [] # 비어있는 리스트 하나 선언
for i in emp_csv :
   emp.append({'empno':i[0],'ename':i[1],'job',i[2],'mgr':i[3],'hiredate':i[4],'sal':i[5],'comm':i[6],'deptno':i[7]})
print(emp)
문제136.emp 딕셔너리 변수에서 이름만 출력하시오 
     그동안에는 emp_list변수에서 ename 에 해당하는 부분ㅇ르 출력해왓다면 
          ---> emp_list[1]
     지금은     emp_dic 변수에서 ename 에 해당하는 부분을 출력하는 것이다ㅣ
          ---> emp_dic[키]

문제137. 이름과 월급과 직업을 출력하시오 !

for emp_dic in emp:
    print(emp_dic['ename'].ljust(10),emp_dic['sal'].ljust(10),emp_dic['job'].ljust(10))


문제138. dept.csv 를 읽어서 딕셔너리 데이터 구조로 저장하고 아래와 같이 
         수행하면  deptno, dname, loc가 출력되게 하시오 


import csv
dept_file = open("D:\data\dept.csv",'r')
dept_csv = csv.reader(file)
dept= [] # 비어있는 리스트 하나 선언
for i in emp_csv :
   emp.append({'deptno':i[0],'dname':i[1],'loc',i[2]})


문제139. emp.csv 와 dept.csv 를 각각 읽어와서 emp_dic, dept_dic
         딕셔너리 자료형으로 만드는 스크립트를 하나로 합치시오 

import csv
dept_file = open("D:\data\dept.csv",'r')
emp_file = open("D:\data\emp.csv",'r')
dept_csv = csv.reader(dept_file )
emp_csv = csv.reader(emp_file)
dept= [] 
emp = []

for i in dept_csv :
  dept.append({'deptno':i[0],'dname':i[1],'loc':i[2]})

for i in emp_csv :
  emp.append({'empno':i[0],'ename':i[1],'job',i[2],'mgr':i[3],'hiredate':i[4],
               'sal':i[5],'comm':i[6],'deptno':i[7]})

문제140. emp와 dept라는 딕셔너리 자료구조를 만드는 스크립트와 중첩  for loop문을 이용해서 
         emp와 dept를 조인 시켜서 ename 과 loc를 출력하시오 

" nested loop 조인 방법 " 

for e in emp:
 for d in dept:
  if e['deptno'] == d['deptno']:
     print( e['ename'],d['loc'])

문제141. 부서위치가 DALLAS 인 사원들의 이름과 부서위치를 출력하시오 ! 

for e in emp:
 for d in dept:
  if (e['deptno'] == d['deptno'])  & (d['loc']  == 'DALLAS'):
     print( e['ename'].ljust(7),d['loc'])

for e in emp:
 for d in dept:
  if (e['deptno'] == d['deptno'])  and (d['loc']  == 'DALLAS'):
     print( e['ename'].ljust(7),d['loc'])

문제142. 위의 스크립트를 이용해서 조인 함수를 생성하시오 ! 

print (join( emp, 'ename',dept,'loc','deptno')) 


def join(t1,col1,t2,col2,jn):
 for e in t1 :
     for d in t2 :
      if e[jn] == d[jn]:
         print( e[col1 ].ljust(7),d[col2])

join( emp, 'ename',dept,'loc','deptno')




문제143. Pandas를 이용해서 ename 과  loc 를 출력하시오 


import pandas as pd

emp= pd.read_csv("D:\data\emp.csv")
dept= pd.read_csv("D:\data\dept.csv")

result  = pd.merge(emp,dept,on='deptno')
print (result[['ename','loc']])


문제144. 부서위치가 dallas인 사원들의 이름과 부서위치를 출력하시오pandas사용
import pandas as pd

emp= pd.read_csv("D:\data\emp.csv")
dept= pd.read_csv("D:\data\dept.csv")

result  = pd.merge(emp,dept,on='deptno')
print (result[['ename','loc']][result['loc']=='DALLAS'])

문제145. 이름과 부서위치를 출력하는데 아래와 같이 Outer join을 구현하시오 

select e.ename, d.loc
  from emp e , dept d
 where e.deptno = d.deptno(+);

import pandas as pd

emp= pd.read_csv("D:\data\emp.csv")
dept= pd.read_csv("D:\data\dept.csv")

result  = pd.merge(emp,dept,on='deptno',how='right')
print (result[['ename','loc']][result['loc']=='DALLAS'])



















'PYTHON' 카테고리의 다른 글

gcp를 이용해서 jupyter notebook / jupyter lab 서버 만들기  (0) 2018.08.27
9장. 객체와 클래스 (가장 중요한 단원)  (0) 2017.09.10
8장. 모듈  (0) 2017.09.10
7장. 함수  (0) 2017.09.10
1-5장  (0) 2017.09.10

1-5장

PYTHON2017. 9. 10. 00:40
   ■ 파이썬을 통해서 우리가 이루고자 하는 목표 2가지
  1. 파이썬 문법 ( ~ 11장. ----> 웹스크롤링 ---> Tic Tac Toe)
                                                      ↓
                                                  1.단층 퍼셉트론
                                                  2.greedy 알고리즘
                                                  3.확률(몬테카를로)

                                                              ↓
                                                       통계학자4명+물리학자

  1. 웹스크롤링 기술

               신문사 ------> 트위터 -----------> 인스타그램

               원하는 사이트를 자유롭게 웹 스크롤링
  1. 머신러닝 프로그램 구현 (Tic Tac Toe - Mit 공대)


점프 투 파이썬


■ 파이썬 설치

인스타그램

■ 파이썬 설치
  1. 기본 파이썬 설치 파일
  1. 아나콘다(spider)

     - 웹스크롤링       : beautiful soup 모듈
     - 머신러닝(틱텍토) : numpy 모듈

  1. 파이참(pycharm)


■ 2장. 파이썬이란?

  1. 파이썬의 문법은 쉽다
  2. 라이브러리 (모듈) 이 많아서 유용하다
           -Numpy 모듈 : 수학 연산에 필요한 모듈
           -beautiful soup 모듈 : 웹스크롤링 모듈
           -pandas 모듈 : 데이터 검색 모듈


■3장. 파이썬 설치

■4장. 데이터 다루기

  • 4장 목차
1.파이썬에서 변수 사용법
2.산순연산자
3.함수
4.input 명령어 사용법

4.1. 파이썬에서 변수 사용법
      • 일반변수   : 변수 안에 데이터가 한 개
               예: a = 1000
                   print(a)


      • 리스트 변수: 변수안에 여러개의 데이터(요소)가 들어있는 변수

a=1000print(a)print(type(a))a='e'print(a)print(type(a))a=1/7.0print(a)print(type(a))a='elrkjer'print(a)print(type(a))a=''print(a)print(type(a))a=nullprint(a)print(type(a))
1000<class 'int'>e<class 'str'>0.14285714285714285<class 'float'>elrkjer<class 'str'>

<class 'str'>






  • 리스트 변수 : 변수안에 여러개의 데이터(요소)가 들어있느 ㄴ변수

d=[1000,2000,3000,4000]
print(d)
print(type(d))
------------------------
[1000, 2000, 3000, 4000]
<class 'list'>


문제1. 위의 d 리스트 변수에서 2000을 출력하시오

d=[1000,2000,3000,4000]
print(d[0])
[결과]
1000

문제2. d 리스트 변수안에 있는 요소드릉르 하나씩 출력하시오 !


d=[1000,2000,3000,4000]
for i in d:
    print(i)
[결과]
1000
2000
3000
4000

설명 : 파이썬은 PL/SQL이나 JAVA, C언어 처럼 ; [세미콜론]을 사용하지 않는다.
       그냥 : [콜론]을 사용하는데 (괄호쓰지않고 ) 반드시 콜론을 끝에 적어줘야하는
       문법이 if 문, while loop, for loop, def 함수 생성시 사용한다.

       PL/SQL 이나 자바,C 등을 사용하던 사람들은 뒤에 ; 을 붙이는 습관이있는데
       파이썬은 기본적으로 구문의 뒤에 아무것도 붙이지 않는다. 대신 IF문이나
     WHILE LOOP, FOR LOOP, DEF CLASS 문의 뒤에 는 꼭 붙여야한다.

     파이썬이 다른 언어보다 보기 쉽고 소스코드가 간결한 이유는
     콜론(:)을 사용해서 들여쓰기를 하도록 만들었기 때문이다.
     파이썬은 블럭구분을 들여쓰기를 통해서 한다.
     콜론(:) 뒤에 나오는 명령어를 다음줄에 작성하려면 들여쓰기를 해야한다.


문제3. a 라는 리스트 변수에 아래의 내용을 담으시오

a = ['7839','KING','PRESIDENT','0','1981-11-17','5000','','10']
for i in a:
    print(i)

문제4. a 리스트에서 7839만 출력하세요

a = ['7839','KING','PRESIDENT','0','1981-11-17','5000','','10']
print(a[0])

  1. 함수
■len 함수 : 리스트 변수안에 있는 요소들이 몇개인지 출력하는 함수

a = ['7839','KING','PRESIDENT','0','1981-11-17','5000','','10']
cnt = len(a)
print(cnt)

a = ['7839','KING','PRESIDENT','0','1981-11-17','5000','','10']
                                                       ↓
                                                      None
                                                    (오라클의 null)

문제6. 카페에서 파이썬 수업자료에 emp2.csv를 내려받아 D 드라이브 밑에
     data라는 폴더에 다운 받고 아래와 같이 수행한다.


import csv

file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
     print (emp_list)


문제7. 위의 결과에서 사원번호만 출력하시오

import csv

file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
     print (emp_list[0])


문제8. 이름과 월급을 출력하시오


import csv

file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:

    print (emp_list[2].rjust(10),emp_list[5].rjust(10))


문제9. 위의 14개의 리스트 변수의 요소의 갯수를 아래와 같이 출력하시오


import csv

file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:

    print (len(emp_list))

결과 :
8
8
8
8
8
8
8
8
8
8
8
8
8
8

문제10. 이름과 이름의 길이를 아래와 같이 출력하시오 !
SMITH 5
SCOTT 5
ALLEN 5


import csv

file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:

    print (emp_list[1] ,len(emp_list[1]))


■ 4.3 산술 연산자
     + 더하기
     - 빼기
     *곱하기
     / 나누기
     % 나눈 나머지 값
문제11. 사원번호, 이름 , 월급을 출력하시오

import csv

file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:

    print (emp_list[0] ,emp_list[1],emp_list[5] )

문제12. 이름과 연봉(sal*12) 을 출력하시오 !
설명 : 숫자로 형변환을 해주어야 한다.
import csv


file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:

    print (emp_list[0] ,emp_list[1],emp_list[5]*12 )
[결과]



설명: 숫자로 형변환을 해주어야 한다.
import csv

file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:

    print (emp_list[0] ,emp_list[1],int(emp_list[5])*12 )



문제13. 이름과 커미션을 출력하는데 커미션이 none 이면 0으로 출력하시오 !


def ifnull(var,val):
if var is '': 
return val
return var

import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
print (emp_list[1] ,ifnull(emp_list[6],0) )

문제14.(오늘의 마지막 문제 ) 이름과 월급 + 커미션을 출력하시오 !


def ifnull(var,val):
 if var is '':
  return val
 return var

import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (emp_list[1] ,int(emp_list[5]) + int(ifnull(emp_list[6],0)) )
[결과]
...
KING 5000
BLAKE 2850
CLARK 2450
JONES 2975
MARTIN 2650
ALLEN 1900
TURNER 1500
JAMES 950
WARD 1750
FORD 3000
SMITH 800
SCOTT 3000
ADAMS 1100
MILLER 1300


def ifnull(var,val):
 if var is '':
  return val
 return var
import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
 print(emp_list[1],int(emp_list[5]),int(emp_list[5])+int(ifnull(emp_list[6],0)),int(emp_list[5])+int(ifnull(emp_list[6],0))-int(emp_list[5]), emp_list[6])



■ 어제 배운 내용
  1. 파이썬을 배우는 목표
ぁ 웹스크롤링 Big data 수집
ぃ 머신 러닝 - Tic Tac Toe 코드로 이해
     엔트로피 지수로 가장 좋은 수를 찾는 방법을 구현 코드

     퍼센트론  -----> 인공신경망
                         ↓
                    행렬, 벡터를 이용한 수학 공식을 계산

                    사람의 뇌 구조를 아주 조금 컴퓨터로 구현했는데
                    그 안에 뉴런에서 보내는 신호를 가중치로 표현을
                    해서 그 가중치(반복학습을 하면 중요하다는 것을 알게되는것 !)
                    를 계산해야 한다.

     2x + 3y + z  = 4
     x -  y  + 3z = 2     연립 방정식 계산식
     5x + 2y + z  = 4

          선형대수학


  1. 데이터 다루기
          - 변수 사용법
          - 산술 연산자
          - nvl 함수가 파이썬에는 없음


     *4장 목차
  1. 변수 사용법
  2. 산술 연산자
  3. 함수
  4. input 명령어

4.3. 함수
책 83 ~ 85
*우리의 목표에 맞춰서 나름대로 다시 정리

오라클
파이썬
1. 문자함수
upper
lower
initcap
substr
replace
length
rtrim
ltrim
trim
rpad
lpad
instr

upper()
lower()
사용자 함수
변수[1:2]
replace()
len()
rstrip()
lstrip()
strip()
사용자 함수
사용자 함수
사용자 함수

2.숫자함수roundtruncmodpower

round()trunc()%power()
3.날짜함수months_betweenadd_monthsnext_daylast_day

사용자 함수
relativedelta사용자 함수monthrange
4.변환함수to_charto_numberto_date

str()int(), float()datetime.strptime()
5.일반함수
nvl
decode
case

사용자함수
 ifnull
사용자함수
if 문
6. 파이썬에 유용한 함수(MIT Tic Tac Toe)문자함수




변환함수


기타(MIT 코드 이해를 위해필수로 알아야하는 중요함수 )


format()isalpha()isnumeric()isspace()

list()tupple()

split
append
range
count

■ 연산자
  1. 산술 연산자
  2. 비교 연산자
  3. 논리 연산자
  4. 기타 비교연산자



오라클
파이썬
산술 연산자

+-

mod
+-/%
비교연산자

= !=>>=<<=

논리연산자

andornot
&|!
기타 비교 연산자
between .. andin, not inis nulllike
<=  & >=in==''^(시작), $(끝) , 정규식함수


문제15. 이름과 직업을 출력하는데 소문자로 출력하시오
---------------------------
 함수 : upper , lower 함수
---------------------------


import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (emp_list[1] ,int(emp_list[5]) + int(ifnull(emp_list[6],0)) )


문제16.(MIT TTT 코드를 이해를 위해 중요한 기초 문제)
        이름을 출력하는데 이름의 첫번째 철자만 출력하고 소문자로 출력하시오!


import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (emp_list[1][:1].lower())


문제17. 이름을 출력하는데 이름의 두번째 철자부터 마지막까지 소문자로

import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (emp_list[1],emp_list[1][1:].lower())

문제18. 이름의 첫번째 함수는 대분자로 나머지는 소문자로 출력하시오
---------------------------
|함수: initcap 사용자 함수|
---------------------------

def initcap(val):
 return  val[0].upper()+val[1:].lower()
import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (initcap(emp_list[1]))

문제19. 이름의 첫번째 철자부터 세번째 철자까지 출력되게하시오 !
---------------------------
|함수: substr 사용자 함수 |
---------------------------

import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (emp_list[1][0:3])

문제20. 이름의 첫번째 철자부터 세번째 철자까지 출력되게하시오 !

def substr (val, num1, num2):
     return val[num1-1:num2]
import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (substr(emp_list[1],1,3) )

문제21. 이름과 월급을 출력하는데 월급을 출력할 때에 0 대신에 * 를 출력하시오

import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (emp_list[5].replace('0','*') )

문제22. 이름과 월급을 출력하는데 월급을 출력할때 0~2를 *로 출력하시오 !
---------------------
|함수: re 정규식함수|
--------------------- 참고사이트 : http://devanix.tistory.com/296
import re
import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (re.sub('[0-2]','*',emp_list[5]) )


sub(pattern, repl, string[, count=0])

문제23. 이름과 이름의 길이를 출력하시오 !
---------------------
|함수: len()        |
---------------------

import csv
file = open("D:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    print (emp_list[1],len(emp_list[1])  )

문제24. 아래의  split 함수의 예제를 수행해보시오!
---------------------
|함수: split()      |
---------------------
file = 'a b c d e f g'

print ( file.split(' ') )
['a' , 'b', 'c' ,'d' , 'e', 'f' ,'g']

문제25. 아래 file 변수의 요소들을 리시트 변수로 담아내서 두번째 요소인 b만 출력해보시오 !
file = 'a b c d e f g'

a = file.split(' ')
print(a[1])
print ( file.split(' ')[3])

문제26. 겨울왕국 대본을 공백을 구분으로 두고 나눠서 리스트 변수로 저장되게 하시오 ! 
---------------------
|함수: split()      |
---------------------

file = open("D:\data\winter.txt",'r')
for winter_list in file:
    a= winter_list.split(' ')
    print (a)
문제27. (점심시간 문제) 위의 스크립트를 이용해서 겨울왕국 각 리스트 변수안에 단어가 몇개 있는지 아래와 같이 출력되게하시오 

file = open("D:\data\winter.txt",'r')
for winter_list in file:
    a=len(winter_list)
    print (a)

문제28."썸! 

file = open("C:\Octave\winter.txt","r" )
b = 0
c = 0
for winter_list in file:
a= winter_list.split(' ')
b = b + len(a)

print(b)

문제29. 카운트 함수 써보자 
---------------------
|함수: count()      |


c = ['Anna','Elsa','Anna','Elsa']
d = c.count('Elsa')
print(d)
[결과]
2

file = open("C:\Octave\winter.txt","r" )
b = 0
c = 0
for winter_list in file:
a= winter_list.split(' ')
b+=a.count('Elsa')

print(b)

문제30. emp.csv 에서 14개의 사원번호를 출력해보자!

import csv
file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
b = []
for emp_list in emp_csv:

    b.append(emp_list[0])
print(b)


예제 :         a = [1, 2, 3]
               a.append(4)
               print(a)

               b = []
               b.append(1)
               b.append(2)
               b.append(3)
               print(b)
문제31. 겨울왕국 대본을 단어별로 출력하시오! 
           
          for loop                          for loop
csv ------------------> list 변수 ----------------------------> 하나의 단어  
                            ↓
     ['glide', 'and', 'pivot.\n']
     ['We', 'pull', 'away', 'slowly,', 'into', 'the', 'sky.', 'We', 'arrive', 'at', 'a', 'bird’s-eye\n']

file = open("D:\data\winter.txt",'r')

for winter_list in file:
   a= winter_list.split(' ')  # 스크립트 -----> 리스트 변수 
   for i in a:                # 리스트 변수 --> 단어
    print(i)

문제32. 위의 출력된 단어들을 하나의  list변수에 담으시오 

---------------------
|함수: append()      |
---------------------

 file = open("D:\data\winter.txt",'r')
B=[]
for winter_list in file:
   a= winter_list.split(' ')
   for i in a:
    B.append(i)

print(B)

문제33. 출력된 단어들 중에서 \n 은 잘라내시오 

-----------------------------------
|함수: lstrip(), rstrip(), strip()|
-----------------------------------

 file = open("D:\data\winter.txt",'r')
B=[]
for winter_list in file:
   a= winter_list.split(' ')
   for i in a:
    i = i.strip('\n')
    B.append(i)

 문제34. rpad 함수를 생성하시오 아래와 같이 실행되게 하시오 !
-----------------------------------
|함수:  rpad(), lpad() 함수       |
-----------------------------------


def rpad(var,val):
if var is '':
return val
return var

import csv

file = open("D:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:

    print (emp_list[1], emp_list[5] )




file = open("D:\data\winter.txt",'r')

a=0

b=0

for winter_list in file:   

        a= winter_list.split(' ')        

        b+=a.count('Elsa')

        

print (b)




     1. 날짜함수를 파이썬으로 생성
      - next_day (사용자 함수)
      - add_months ( 모듈 이용해서 구현)
      - last_day ( monthrange 함수)
      - months_between ( 사용자 함수) ---> ? 오래 생각해야할 문제
   2. input 명령어 + if 문 사용
   3. 비교 연산자 : ==
             >=
             <=
             !=
              >
              <
             in <----- 겨울왕국에서 긍정단어가 몇 개가 있는가?

   ■ 기타 비교연산자 :
   in   in
   between .. and    <= & >=
   like   정규식 함수
   is null   ==''

   ■논리 연산자:
   and   &
   or   |
   not   ^


문제62. 직업이 SALESMAN 이고 월급 1200 이상인 사원들의 이름과 직업과 월급을 출력하시오 !

import csv
file = open("d:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    if (emp_list[2] == 'SALESMAN') & (int(emp_list[5]) >= 1200):
        print(emp_list[1], emp_list[5])




문제63. 월급이 1000에서 3000 사이인 사원들의 이름과 월급을 출력하시오 !
연산자:   between .. and |

import csv
file = open("d:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    if (1000 <= int(emp_list[5])) & (3000 >=int(emp_list[5])):
        print(emp_list[1], emp_list[5])




문제64. 직업이 ANALYST, CLERK 인 사원들의 이름과 월급과 직업을 출력하시오 !
연산자:   in |
import csv
file = open("d:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    if emp_list[2] in ['ANALYST','CLERK']:
        print(emp_list[1], emp_list[5], emp_list[2])


문제65. 직업이 ANALYST, CLERK 이 아닌 사원들의 이름과 월급과 직업을 출력하시오 !
연산자:   in |

import csv
file = open("d:\data\emp2.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    if emp_list[2] not in ['ANALYST','CLERK']:
        print(emp_list[1], emp_list[5], emp_list[2])




문제66. 커미션이 null 인 사원들의 이름과 커미션을 출력하시오 !

   4. 파이썬 수업용 실습 데이터의 emp_comm.csv 를 다운받아서 수행
   연산자 :    is null
import csv
file = open("d:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    if emp_list[6] =='':
        print(emp_list[1], emp_list[6])



문제67. 커미션이 null 이 아닌 사원들의 이름과 커미션을 출력하시오 !
연산자:   ins not null

import csv
file = open("d:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    if emp_list[6] !='':
        print(emp_list[1], emp_list[6])




문제68. 이름의 첫번째 철자가 S 로 시작하는 사원들의 이름과 월급을 출력하시오 !
연산자:   like

import csv
file = open("d:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    if emp_list[1][0:1] =='S':
        print(emp_list[1], emp_list[6])




문제69. 이름의 두번쨰 철자가 M 인 사원들의 이름과 우러급을 출력하시오 !
연산자:   like

import csv
file = open("d:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    if emp_list[1][1:2] =='M':
        print(emp_list[1], emp_list[5])



문제70. 이름의 마지막 철자가 H인 사원들의 이름과 월급을 출력하시오 !
연산자:   like       

import csv
file = open("d:\data\emp_comm.csv",'r')
emp_csv = csv.reader(file)
for emp_list in emp_csv:
    if emp_list[1][-1] =='H':
        print(emp_list[1], emp_list[5])







'PYTHON' 카테고리의 다른 글

gcp를 이용해서 jupyter notebook / jupyter lab 서버 만들기  (0) 2018.08.27
9장. 객체와 클래스 (가장 중요한 단원)  (0) 2017.09.10
8장. 모듈  (0) 2017.09.10
7장. 함수  (0) 2017.09.10
6장. if 문과 loop문 (p126)  (0) 2017.09.10