2016년 7월 29일 금요일

[Python] pyenv 로 Python 버전 및 개발 환경 관리

pyenv 로 Python 버전 및 개발 환경 관리

설치

  • OS X
    $ brew update
    $ brew install pyenv
    $ brew install pyenv-virtualenv
    
  • 기타 OS
    1. installer 활용 설치
      $ curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash
      
    2. PATH 설정
      • ~/.bash_profile 에 다음 내용 추가
      export PATH="~/.pyenv/bin:$PATH"
      eval "$(pyenv init -)"
      eval "$(pyenv virtualenv-init -)"
      
      • 적용
      $ source ~/.bash_profile
      

사용

  1. pyenv로 Python 설치
    • 설치 가능 버전 확인
    $ pyenv install --list
    
    • 설치는 `pyenv install 3.5.2' 형태로 가능
  2. pyenv-virtualenv 로 가상 환경 관리
    https://github.com/yyuu/pyenv-virtualenv
    pyenv-installer 에 포함이 되어있기 때문에 추가로 설치할 것은 없다.
    1. 가상 환경 생성
      $ pyenv virtualenv 3.5.2 v352
      
      • pyenv virtualenv 버전 환경명 형태로 사용
      • 버전을 지정하지 않으면 현재 지정된 버전으로 적용됨
    2. 가상 환경 활성화
      $ pyenv activate v352
      
      • pyenv activate 환경명 형태로 사용
      • pyenv deactivate 로 비활성화


2016년 7월 25일 월요일

[Algorithm] Codility Lesson 7 Stacks and Queues - Brackets



A string S consisting of N characters is considered to be properly nested
if any of the following conditions is true:
        - S is empty;
        - S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
        - S has the form "VW" where V and W are properly nested strings.

For example, the string "{[()()]}" is properly nested but "([)()]" is not.

Write a function:
        class Solution { public int solution(String S); }
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.

For example, given S = "{[()()]}", the function should return 1
and given S = "([)()]", the function should return 0, as explained above.

Assume that:
        - N is an integer within the range [0..200,000];
        - string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".

Complexity:
        - expected worst-case time complexity is O(N);
        - expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
     

===============================================================================

N개의 문자로 구성된 문자열 S는 다음 조건 중 하나라도 true일 경우 제대로 중첩된다고 간주된다.
        - S는 공백이다;
        - S가 "(U)" 또는 "[U]" 또는 "{U}" 형태를 가지고 U는 제대로 중첩된 문자열이다.;
        - S가 "VW" 형태를 가지고 V와 W는 제대로 중첩된 문자열이다.

예를 들어, 문자열 "{[()()]}"는 제대로 중첩되었지만 "([)()]" 는 그렇지 않다.

함수 작성:
        class Solution { public int solution(String S); }
N개의 문자로 구성된 문자열 S가 주어지고, S가 제대로 중첩된 경우 1을 리턴하고 그렇지 않으면 0을 리턴한다.

예를 들어, S = "{[()()]}" 가 주어지면 함수는 1을 리턴해야 하고,
S = "([)()]" 가 주어지면 위에서 설명한 것처럼 함수는 0을 리턴해야 한다.

가정:
        - N은 [0..200,000] 범위의 정수
        - 문자열 S는 다음 문자로만 구성된다: "(", "{", "[", "]", "}", ")".

복잡도:
        - 최악의 시간 복잡도는 O(N);
        - 최악의 공간 복잡도는 O(N) (입력 공간 제외).

===============================================================================


100%:
https://codility.com/demo/results/trainingHXGBJ5-V8X/



2016년 7월 5일 화요일

[Django] Django Tutorial 1





Django Tutorial


설치

  1. python 설치
  2. Django 설치
    • pip install Django
    • 설치 확인은 python -m django --version

프로젝트 생성

  1. 커맨드로 기본 프로젝트 구조 생성
    • django-admin startproject mysite
  2. 생성 파일 확인
    mysite/
        manage.py
        mysite/
            __init__.py
            settings.py
            urls.py
            wsgi.py
    
    • 바깥쪽 mysite/ 폴더는 프로젝트를 감싸는 역할을 하고, 이름은 Django 에게 중요하지 않아서 원하면 바꿔도 된다.
    • manage.py : Django 프로젝트와 상호작용 할 수 있도록 해주는 커맨드라인 유틸리티이다. 더 상세한 내용은 django-admin and manage.py 에서 확인할 수 있다.
    • 안쪽 mysite/ 폴더는 프로젝트를 위한 실제 Python 패키지이다. 이 폴더명은 Python 패키지 이름이 되며 안에 있는 것을 import 하려면 이 이름을 사용해야 한다. (예: mysite.urls).
    • mysite/__init__.py : Python에게 이 디렉토리가 Python 패키지라고 간주하도록 하는 빈 파일이다. Python 초심자라면 공식 Python 문서인 more about packages를 읽어라.
    • mysite/settings.py 이 Django 프로젝트의 설정이다. Django settings에서 설정하는 방법에 대해 알려준다.
    • mysite/urls.py : 이 Django 프로젝트의 URL 선언이다; Django로 생성된 사이트의 목차이다. (URL dispatcher)[https://docs.djangoproject.com/en/1.9/topics/http/urls/]에서 URL에 대해 더 읽을 수 있다.
    • mysite/wsgi : 프로젝트를 WSGI 호환 웹 서버로 제공하기 위한 엔트리 포인트이다. (How to deploy with WSGI)[https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/]에서 WSGI과 함께 배포하는 방법에 대한 자세한 내용을 참조할 수 있다.

개발 서버 실행

  1. 실행
    • 바깥쪽 mysite 폴더로 이동한 뒤 커맨드를 이용해 실행한다. python manage.py runserver
    • 실행시 나오는 데이터베이스 관련 경고는 곧 다룰 것이므로 지금은 무시한다.
    • Django 에 경량 웹서버를 포함해두어서 배포 전 까지 Apache 등의 서버 설정을 고려하지 않고 빠르게 개발할 수 있다.
    • 개발 서버는 실제 환경에서 사용하지 말고 개발 중에만 사용하도록 한다.
  2. 접속 확인



2016년 7월 2일 토요일

[Algorithm] Codility Lesson 7 Stacks and Queues - Fish

You are given two non-empty zero-indexed arrays A and B consisting of N integers.
Arrays A and B represent N voracious fish in a river,
ordered downstream along the flow of the river.

The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q,
then fish P is initially upstream of fish Q. Initially, each fish has a unique position.

Fish number P is represented by A[P] and B[P].
Array A contains the sizes of the fish. All its elements are unique.
Array B contains the directions of the fish. It contains only 0s and/or 1s, where:
- 0 represents a fish flowing upstream,
- 1 represents a fish flowing downstream.

If two fish move in opposite directions and there are no other (living) fish between them,
they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one.
More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0,
and there are no living fish between them. After they meet:
- If A[P] > A[Q] then P eats Q, and P will still be flowing downstream,
- If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream.
We assume that all the fish are flowing at the same speed.
That is, fish moving in the same direction never meet.
 The goal is to calculate the number of fish that will stay alive.

For example, consider arrays A and B such that:
- A[0] = 4    B[0] = 0
- A[1] = 3    B[1] = 1
- A[2] = 2    B[2] = 0
- A[3] = 1    B[3] = 0
- A[4] = 5    B[4] = 0
Initially all the fish are alive and all except fish number 1 are moving upstream.
Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too.
Finally, it meets fish number 4 and is eaten by it. The remaining two fish,
number 0 and 4, never meet and therefore stay alive.

Write a function:
class Solution { public int solution(int[] A, int[] B); }
that, given two non-empty zero-indexed arrays A and B consisting of N integers,
returns the number of fish that will stay alive.

For example, given the arrays shown above, the function should return 2, as explained above.

Assume that:
- N is an integer within the range [1..100,000];
- each element of array A is an integer within the range [0..1,000,000,000];
- each element of array B is an integer that can have one of the following values: 0, 1;
- the elements of A are all distinct.
Complexity:
- expected worst-case time complexity is O(N);
- expected worst-case space complexity is O(N), beyond input storage
(not counting the storage required for input arguments).

Elements of input arrays can be modified.

==============================================================================

N개의 정수로 구성된 배열 A와 B가 주어진다. 배열 A와 B는 강의 흐름에 따라 순서가 매겨진,
강 안의 게걸스러운 물고기 N마리를 나타낸다.

물고기는 0부터 N-1 까지로 숫자가 매겨져 있다. 만약 P < Q인 두 물고기가 있다면,
물고기 P는 물고기 Q보다 초기에 상류에 있다. 초기에 각 물고기는 유일한 위치를 가진다.

물고기 P는 A[P]와 B[P]로 표현된다. 배열 A는 물고기의 크기를 포함한다. 모든 요소는 유일하다.
배열 B는 물고기의 방향을 포함한다. 오직 0 또는 1만 포함한다.
- 0은 물고기가 상류로 흐르고 있음을 나타내고,
- 1은 물고기가 하류로 흐르고 있음을 나타낸다.

만약 두 물고기가 반대되는 방향으로 움직이고 그 사이에 (살아있는) 다른 물고기가 없다면,
그들은 결국 서로 만나게 된다. 그렇게 되면 오직 한 물고기만 살아남을 수 있다
- 더 큰 물고기가 작은 물고기를 먹는다. 더 정확하게는 P < Q,  B[P] = 1, B[Q] = 0 이고
그사이에 살아있는 물고기가 없는 물고기 P와 Q가 서로 만나게 되면 그들이 만난 이후에는
- 만약 A[P] > A[Q]이면 P가 Q를 먹고 P는 계속 하류로 흐르고,
- 만약 A[P] < A[Q]이면 Q가 P를 먹고 Q는 계속 상류로 흐른다.

모든 물고기는 같은 속도로 흐른다고 가정한다. 물고기가 같은 방향으로 움직인다면
절대 만나지 않는다는 것이다. 목표는 살아남은 물고기의 숫자를 구하는 것이다.

예를 들어, 배열 A와 B가 다음과 같다고 생각하면:
A[0] = 4    B[0] = 0
A[1] = 3    B[1] = 1
A[2] = 2    B[2] = 0
A[3] = 1    B[3] = 0
A[4] = 5    B[4] = 0
초기에는 모든 물고기가 살아있고, 물고기 1을 제외한 모든 물고기가 상류로 움직인다.
물고기 1은 물고기 2를 만나고 먹는다. 그리고 물고기 3을 만나서 역시 먹는다.
마지막으로 물고기 4를 만나서 먹힌다. 남은 두 물고기 0과 4는 절대 만나지 않고 영원히 살아남는다.

함수 작성
class Solution { public int solution(int[] A, int[] B); }
N개의 정수로 구성된 배열 A와 B가 주어지고, 살아남은 물고기의 숫자를 리턴한다.

예를 들어, 위에 본 배열들이 주어진다면, 위에서 설명한 것처럼 함수는 2를 리턴해야한다.

가정:
- N은 [1..100,000] 범위의 정수;
- 배열 A의 요소는 [0..1,000,000,000] 범위의 정수;
- 배열 B의 요소는 다음 값 중 하나를 가질 수 있다: 0, 1;
- 배열 A의 요소는 모두 다르다.

복잡도:
- 최악의 시간복잡도는 O(N);
- 최악의 공간복잡도는 O(N), 입력 공간 제외

배열의 요소는 수정될 수 있다.

==============================================================================


100%:
https://codility.com/demo/results/trainingDA4BVB-S6N/