Friday, October 5, 2012

Often we run into situation to check what version we are running for particular framework, language, module.

Here, I have tried to list down the one I come across during my work -

Go to Python shell and follow below instruction for individual.

Django

>>> import django
>>> print django.VERSION
(1, 3, 1, 'final', 0)

Python

>>> import sys
>>> print sys.version
2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)]

NLTK

>>> import nltk
>>> nltk.__version__
'2.0.1rc4'

dateutil

>>> import dateutil
>>> dateutil.__version__
'1.5'

- Important thing to note here is python-dateutil 2.0 is not compatible with python 2.7 it only works with python 3.0. For 2.7 please try 1.5

-If you have 2.0, first uninstall and then install specific one

\$ pip uninstall python-dateutil

\$ pip install python-dateutil==1.5

Thursday, October 4, 2012

Sympy - Superb python library

Recently we came across requirement where we need to evaluate/compare/validate the algebra equation.

Different ways to do it -

- Use eval() function of python
>>> x = 2

>>> eval("x+2")
4

- Use Regex - Not a practical approach

- Use Sympy - works for simple cases which we are interested in, though probably we are just using the <10% of it.
>>> from sympy import *
>>> x = Symbol('x')
>>> y = Symbol('y')

>>> simplify(2*x+y)
2*x + y
>>> simplify(y+2*x)
2*x + y

p.s. both 2x+y and y+2x is same thing.

>>> simplify(2*(x+7)) == simplify(2*x + 14)
True
>>> simplify(2*(x+7)) == simplify(2*x + 13)
False
>>> simplify(2*(y+7)) == simplify(2*x + 14)
False
>>> simplify(2*(y+7)) == simplify(2*y + 14)
True

Here is the interesting one though -
>>> simplify((1/2) * 7*x) == simplify(7*x / 2)
False
>>> simplify(0.5 * 7*x) == simplify(7*x / 2)
True
>>> simplify((1.0/2.0) * 7*x) == simplify(7*x / 2)
True

Because in python if you specify 1/2, the answer is 0 as it consider it as positive integer, to get the decimal points you need to use 1.0/2.0

It can do expand the equation for you too -
>>> expand((x+y)**6)

x**6 + 6*x**5*y + 15*x**4*y**2 + 20*x**3*y**3 + 15*x**2*y**4 + 6*x*y**5 + y**6