analitics

Pages

Showing posts with label functions. Show all posts
Showing posts with label functions. Show all posts

Tuesday, October 2, 2012

Tuples can put you in difficulty.

They are two examples of sequence data types in python.

Today I will tell about tuples.

A tuple consists of a number of values separated by commas.

The biggest problem is when we do not know the number of these values ​​or type.

Let me illustrate with a function that returns a tuple.

This is a known tuple but we will use like an unknown tuple.

Let's see the python code and some errors:

>>> import sys
>>> if hasattr(sys, 'version_info'):
...     print sys.version_info()
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: 'tuple' object is not callable

Is very correct to got this error.

And the result using the print function:

>>> if hasattr(sys, 'version_info'):
...     print "%s" % str(sys.version_info)
... 
(2, 6, 4, 'final', 0) 

>>> if hasattr(sys, 'version_info'):
...     sys.stderr.write("%s" % str(sys.version_info))
... 
(2, 6, 4, 'final', 0)>>> 

or if you can use the repr function.


>>> if hasattr(sys, 'version_info'):
...     sys.stderr.write("%s" % repr(sys.version_info))
... 
(2, 6, 4, 'final', 0)>>> 

The official Python documentation says __repr__ is used to compute the “official” string representation of an object and __str__ is used to compute the “informal” string representation of an object.

In my opinion , the correct way it's to use repr. For example:

>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2012-10-02 22:45:57.634977'
>>> repr(today)
'datetime.datetime(2012, 10, 2, 22, 45, 57, 634977)'

As we see all values from tuples it's show.

Sunday, September 25, 2011

Tips and tricks with Python ...

Sometimes when using new modules, we are confronted with the following problem.
The modules come with many features that are not fully documented.
Some of them we do not know.
We can use the dir function, but in most cases the result is a huge list.
Here is a simple detection method.
$ python
Python 2.7.1 (r271:86832, Apr 12 2011, 16:16:18)
[GCC 4.6.0 20110331 (Red Hat 4.6.0-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gnome
>>> dirlist=dir(gnome)

I put content above command in a list.
We need to processed now.
>>> dirlist.index('ui')
Traceback (most recent call last):
File "", line 1, in
ValueError: 'ui' is not in list
>>> dirlist.index('sound_play')
118

Here I found an item. To know something about it.
>>> help(dirlist[118])
no Python documentation found for 'sound_play'

Nothing about this. Let's use the command dir.
>>> dir(dirlist[118])
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Using the examples above, you can create a script to parse this source code and check if the functions are the same as our version.

Saturday, July 3, 2010

The module matplotlib-0.99.3

The module matplotlib is a python 2D plotting library with a variety of hardcopy formats and interactive environments across platforms.
With just a few lines of code we can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc...
See images bellow or visit the gallery.

This module is version 0.99.3 for Python 2.5 and 2.6. We have modules for installation on operating systems like MacOS, Windows and Linux.
To use this module you must have install numpy module.
Now download module from here.
$python setup.py build
Use super user:
#python setup.py install
Try to load module:
$python
Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) 
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> 
It's working fine.

Wednesday, May 19, 2010

The beauty of Python: Simple functions - part 1

Validation of a condition and return result in 'Yes' or 'No'.

>>> def valid(x,y):
...     return ('Yes' if x==y else 'No') 
... 
>>> valid(2,3)
'No'
>>> valid(2,2)
'Yes'


Some usefull functions from string module .

>>> import string 
>>> var_template_string=string.Template(" The $subj $vb $something")
>>> var_template_string.substitute(subj="PC", vb="working", something="now")
' The PC working now'
>>> some_string_dictionary={'subj':'car', 'vb':'is', 'something':'blue'}
>>> var_template_string.substitute(some_string_dictionary)
' The car is blue'
>>> some_string_dictionary


Some example with re module and html tag

>>> import re
>>> t='<p>'
>>> some_tag = re.compile(r'<(.*?)(\s|>)')
>>> m = some_tag.match(t)
>>> print m
<_sre.SRE_Match object at 0xb7f79da0>
>>> dir(m)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start']
>>> print m.start()
0
>>> print m.groups()
('p', '>')
>>> print m.group()
<p>
>>> print m.span()
(0, 3)

The re module has many usefull functions.
This is just some examples to show the simplicity of python language.