Thursday, August 27, 2009

Writing factorial function in Python - newbie

The recursive version:

import sys

Usage = """
$ python

def fact(x):
if x == 0:
return 1
return x * fact(x-1)

if (len(sys.argv)>1) :
print fact(int(sys.argv[1]))
print Usage


$ python 6

A shorter version of the above:

import sys

Usage = """
$ python

def fact(x):
return (1 if x==0 else x * fact(x-1))

if (len(sys.argv)>1) :
print fact(int(sys.argv[1]))
print Usage

Or a non-recursive version

def fact(x):
f = 1
while (x > 0):
f = f * x
x = x - 1
return f

And in python 2.6, Math module (Mathematical functions) provides factorial function (math.factorial(x))

$ /jks/bin/python2.6
Python 2.6.2 (r262:71600, Jun 17 2009, 22:31:41)
[GCC 3.3.3 (Debian 20040306)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.factorial(6)

Related concepts:
- Python math module

Tuesday, August 25, 2009

Performing multiple split in python

This post is mainly for python newbies.
Input file:

$ cat data.txt
File Start

Required: Extract the 3 rd field (colored blue) from the above file. i.e. required output:


Here we would need to split the required lines twice (one for field separator : and then for comma) to extract the desired column.

Using bash cut command or awk, the solution would be:
$ grep ^Gid data.txt | cut -d":" -f2 | cut -d"," -f2
$ awk -F"[:,]" '/^Gid/{print $3}' data.txt

The python code:

for line in open("data.txt"):
if line.startswith("Gid"):
print line.split(":")[1].split(",")[1]

Friday, August 14, 2009

Get your ip address in python

Python socket module provides the following functions you can get the IP address of your machine.

>>> import socket
>>> print socket.gethostname()
>>> print socket.gethostbyname(socket.gethostname())
>>> socket.gethostbyaddr(socket.gethostbyname(socket.gethostname()))
('', ['k172-16-0-12'], [''])

Few definitions:

gethostbyname (hostname)
Translate a host name to IP address format. The IP address is returned as a string

gethostname ()
Return a string containing the hostname of the machine where the Python interpreter is currently executing. If you want to know the current machine's IP address, use socket.gethostbyname(socket.gethostname()). Note: gethostname() doesn't always return the fully qualified domain name; use socket.gethostbyaddr(socket.gethostname())

gethostbyaddr (ip_address)
Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the primary host name responding to the given ip_address, aliaslist is a (possibly empty) list of alternative host names for the same address, and ipaddrlist is a list of IP addresses for the same interface on the same host (most likely containing only a single address). To find the fully qualified domain name, check hostname and the items of aliaslist for an entry containing at least one period.

Read more about Built-in Module socket here

Another link to "Determine the IP address of an eth interface"