Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Wednesday, April 16, 2008

Python: py2exe setup file example

py2exe is a Python package that can convert Python scripts into executable Windows programs. This is an example of py2exe setup file.
from distutils.core import setup
import py2exe
import sys

# no arguments
if len(sys.argv) == 1:
    sys.argv.append("py2exe")

def compile(appName, console=False):
    OPTIONS = {"py2exe":
             {"compressed": 1, "optimize": 0, "bundle_files": 1, } }
    ZIPFILE = None
if console:
        setup(
            options=OPTIONS,
            zipfile=ZIPFILE,
            console=[appName]
        )
    else:
        setup(
            options=OPTIONS,
            zipfile=ZIPFILE,
            windows=[appName]
        )
compile(‘example.py’)

Python: Initialize list and tuple values

This tutorial will show on how to give a Python list an initial value.

To initialize a ten items list with values set to 0:
myList = [0]*10
If we need to have 5 items of a list with the value 0 and the rest 5 with the value 1:
myList = [0]*5 + [1]*5
To initialize a ten items tuple with values set to 0:
myTuple = (0,)*10
If we need to have 5 item in a tuple with the value 0 and the rest 5 with the value 1:
myTuple = (0,)*5 + (1,)*5
For list, don't forget the comma ','. It means one item.

Python: Make division always produce real numbers

A division of 7/3 in Python will gives a result of 2. However, this is not correct. Since Python always assume that the numbers are whole numbers, the result will be truncated from 2.5 to 2.

A work around is to write one or both of the numbers as a decimal:
>>> print 7/3.0
2.5

>>> print 7.0/3
2.5

>>> print 7.0/3.0
2.5
In order to change this behaviour of Python, throughout the program execution, so that Python will always produce real numbers, a module division has to be imported.
>>> from __future__ import division

>>> print 7/3
2.5

Python: Put comma(s) to numbers

This script will put commas between each group of three digits number. For example, 1234567 will become 1,234,567.
import re

putComma = lambda x: (",".join(re.findall("d{1,3}",
str(x)[::-1])))[::-1]

print putComma(1234567) # 1,234,567
print putComma(12345678) # 12,345,678
print putComma(123456789) # 123,456,789
print putComma(1212) # 1,212

Python: Prime Number

This Python script will generate a list of prime number.
def isPrime(x):
    for i in range(2, x):
        if x%i == 0:
            return false
        return true

for c in range(1,10):
    if isPrime(c):
        print c,
output:
>>> 1 2 3 5 7