# A Python Library to create a Progress Bar.
# Copyright (C) 2008  BJ Dierkes <wdierkes@5dollarwhitebox.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
# This class is an improvement from the original found at:
#
#   http://code.activestate.com/recipes/168639/
#

import sys,os

class ProgressBar:
    def __init__(self, min_value = 0, max_value = 100, width=77,**kwargs):
        self.char = kwargs.get('char', '#')
        self.mode = kwargs.get('mode', 'dynamic') # fixed or dynamic
        if not self.mode in ['fixed', 'dynamic']:
            self.mode = 'fixed'

        self.bar = ''
        self.min = min_value
        self.max = max_value
        self.span = max_value - min_value
        self.width = width
        self.amount = 0       # When amount == max, we are 100% done
        self.update_amount(0)


    def increment_amount(self, add_amount = 1):
        """
        Increment self.amount by 'add_ammount' or default to incrementing
        by 1, and then rebuild the bar string.
        """
        new_amount = self.amount + add_amount
        if new_amount < self.min: new_amount = self.min
        if new_amount > self.max: new_amount = self.max
        self.amount = new_amount
        self.build_bar()


    def update_amount(self, new_amount = None):
        """
        Update self.amount with 'new_amount', and then rebuild the bar
        string.
        """
        if not new_amount: new_amount = self.amount
        if new_amount < self.min: new_amount = self.min
        if new_amount > self.max: new_amount = self.max
        self.amount = new_amount
        self.build_bar()


    def build_bar(self):
        """
        Figure new percent complete, and rebuild the bar string base on
        self.amount.
        """
        diff = float(self.amount - self.min)
        percent_done = int(round((diff / float(self.span)) * 100.0))

        # figure the proper number of 'character' make up the bar
        all_full = self.width - 2
        num_hashes = int(round((percent_done * all_full) / 100))

        if self.mode == 'dynamic':
            # build a progress bar with self.char (to create a dynamic bar
            # where the percent string moves along with the bar progress.
            self.bar = self.char * num_hashes
        else:
            # build a progress bar with self.char and spaces (to create a
            # fixe bar (the percent string doesn't move)
            self.bar = self.char * num_hashes + ' ' * (all_full-num_hashes)
       
        percent_str = str(percent_done) + "%"
        self.bar = '[ ' + self.bar + ' ] ' + percent_str


    def __str__(self):
        return str(self.bar)


def main():
    print
    limit = 1000000

    print 'Example 1: Fixed Bar'
    prog = ProgressBar(0, limit, 77, mode='fixed')
    oldprog = str(prog)
    for i in xrange(limit+1):
        prog.update_amount(i)
        if oldprog != str(prog):
            print prog, "\r",
            sys.stdout.flush()
            oldprog=str(prog)

    print '\n\n'

    print 'Example 2: Dynamic Bar'
    prog = ProgressBar(0, limit, 77, mode='dynamic', char='-')
    oldprog = str(prog)
    for i in xrange(limit+1):
        prog.increment_amount()
        if oldprog != str(prog):
            print prog, "\r",
            sys.stdout.flush()
            oldprog=str(prog)

    print '\n\n'
   

if __name__ == '__main__':
    main()
,

아바쿠스 내장 파이썬에서 NumPy나 SciPy이 임포팅 안되는 이유는?

파이썬은 2바이트(UCS2)나 4바이트 유니코드(UCS4)로 빌드할 수 있고, 다른 방식으로 빌드된 모듈을 임포팅할수 없다. 빌딩 방식의 차이가 임포팅 문제의 원인을 대부분 제공한다.

 

아바쿠스 파이썬은 2바이트로 빌드 되어 있고 따라서 NumPy나 SciPy가 4바이트로 빌드되어 있다면 당연 임포트 할수 없다.

 

UCS4로 빌드되어 있는지 확인하려면 sys.maxunicode 속성을 확인하면 된다. 이게 65535이면 2바이트 이고 1114111이면 4바이트 빌드다.

 

>>>import sys

>>>print sys.maxunicode

독립 설치된 파이썬 4바이트 빌드라면 2바이트 파이썬을 설치하라 그래야 아바쿠스 내장 파이선에서 모듈을 임포팅할 수 있다.

,

To determine whether scipy is causing the problem or not, run scipy.test() non-interactively. E.g.


$python -c "import scipy; scipy.test()"


,

한줄에 복합문을 사용하는 경우 읽기 어려운 코드를 만들 수도 있기 때문에 그러지 않기를 바라며, 경험적으로 각 문을 별도의 행에 쓰는 것이 좋다.6개월 후면 그렇게 한 것에 대해서 만족할 것이다.


파이썬 부울 연산자를 사용하는 한가지 보편적인 방법은 하나 이상의 객체를 or문으로 선택하는 것이다. x = A or B or C 라는 문은 A,B,C중 비지 않은(nonempty, true) 첫번째 객체를 x에 설정한다. 부울 연산자의 오른쪽에 있는 표현식이 함수 호출 등의 많은 일을 하거나, 단락회로규칙의 효과로 인해 발생하지 않을 부작용을 가질지도 모르기 때문에 '단락 회로식 계산'은 중요한 개념이다.

경험상으로 클래스는 임의의 객체와 그 객체의 관계를 표현할 수 있다. 즉, 관계를 문장으로 표현할 수 있는데, 문장에서 명사를 클래스로 바꾸고, 동사를 메소드로 바꾸면, 설계의 첫 구성을 얻게 된다.
,

윈도우즈에서 사용하던 파이썬 시스템을 맥에서 즐기기위해선
준비할게 제법된다. enthought 아들 빨리 맥도 패키징 좀!
Python 2.4.3 for Windows (Enthought Edition) also includes the following packages:

celementtree 1.0.5-20051216: C extension XML parsing
ctypes 0.9.9.6: A package to create and manipulate C data types in Python
Docutils 0.3.9: text processing system elementtree 1.2.6-20050316: XML parsing Enthought Tool Suite 1.0.9: A tool suite for building extensible python applications. This includes chaco, traits, kiva, envisage, etc.
epydoc 2.0: Automatic API Documentation Generation for Python
fpconst 0.7.2: Utilities for handling IEEE 754 floating point special values
GadflyZip: An SQL Relational Database in Python
IPython 0.7.2: A Python Shell done right. Matplotlib 0.87.3.2478: Python 2D plotting library
MayaVi 1.5: 3D Data Visualization Tool
numarray 1.5.1: STScI rework of Numeric
Numeric 24.2: Numerical Python
NumPy 0.9.9.2706: Basic N-Dimensional Array manipulations
PIL 1.1.5: Python Imaging Library
pydot 0.9.10: Python interface to Graphviz's Dot language
pyparsing 1.4.1: Python based grammar parser
pyreadline 1.3: ctypes-based readline for Windows
pyserial 2.2: A python extension for accessing the serial port
PySQLite 2.2.2: A Python Extension for the SQLite embedded relational database
pysvn 1.4.1: Python interface to subversion version control system
pytables 1.2.3: Package for handling hierarchical datasets
pywin32 208: Python for Windows Extensions
PyXML 0.8.4: XML Tools
ScientificPython 2.4.11: A collection of Python modules for scientific computing
SciPy 0.5.0.2033: Scientific Library for Python
SOAPpy 0.11.6: SOAP/XML Schema library
TestOOB 1.1: Advanced unit testing framework
VTK 5.0: 3D Visualization Toolkit
wxPython 2.6.1.0: wxWindows for Python
ZODB3 3.6: ZODB and ZEO Object DataBase
,

import this

from 카테고리 없음 2007. 10. 31. 06:49
사용자 삽입 이미지

Definitely pythonic!!
,

Numpy

from 카테고리 없음 2007. 10. 16. 10:10
NumPy

파이썬에서 과학 계산을 위해 필요한 기본적인 패키지를 NumPy(넘피)라고 하다. 이패키지는 다음의 기능을 가지고 있다.

-강력한 N차원 배열 객체
-새련된 함수(^^)
-기본적인 선형 대수 함수
-기본적인 푸리에변환 함수
-정교한 난수 발생기능
-포트란과의 통합을 위한 툴

기존의 Numarray/Numeric 패키지와도 변환과정을 거치면 호환성을 가지고 있다.
메인 개발자인 Travis Oliphant가 쓴 책을 사는것도 방법이지만, 무료 문서들을 scipy 웹사이트에서 참조하는 것도 방법이다.

참고링크:
매트랩사용자를 위한 넘피소개
예제로보는 넘피명령어
싸이피/넘피 쿡북


,

Frequency test

from 카테고리 없음 2007. 10. 13. 05:37

리스트등에서 반복되는 문자를 찾아내 그 횟수를 알아내는 파이썬 스런 방법

역시 파이썬은 라이브러리를 잘알아야 진도가 나갈듯.


  1. >>> import itertools
    >>> x = [1,2,2,4,4,4,5,5,1,1]
    >>> dict((k, len(list(v))) for k, v in itertools.groupby(sorted(x)))
    {1: 3, 2: 2, 4: 3, 5: 2}


출처: 한국파이썬사용자그룹

이 글은 스프링노트에서 작성되었습니다.

,