Python Useful Things

Creando pares ordenados:

>>> x=[1, 3, 5]
>>> y=[1, 3, 5, 7]
>>> c1=[(i, j) for i in x for j in y if i != j]
>>> c1
[(1, 3), (1, 5), (1, 7), (3, 1), (3, 5), (3, 7), (5, 1), (5, 3), (5, 7)]
>>> c2=[(i, j) for i in x for j in y]
>>> c2
[(1, 1), (1, 3), (1, 5), (1, 7), (3, 1), (3, 3), (3, 5), (3, 7), (5, 1), (5, 3), (5, 5), (5, 7)]

Convert int to hex string

>>> hex(5)
'0x5'
>>> type('0x05')
<type 'str'>

Convert hex string to int

>>> int('0x5',16)
5

Define a Colormap:
A Color Map is a table that contains a list of input data and defines the color value corresponding to each data value. If you are interested in colormap, read this Link.
Also some scalar colors are useful to know: Link

DL_colorbar4.png
DL_colormap4.png
DL_colorbar5.png
DL_colormap5.png

Triangulo de Pascal:

def trianguloPascal(n):
    lista = [[1],[1,1]]
    for i in range(1,n):
        linha = [1]
        for j in range(0,len(lista[i])-1):
            linha += [ lista[i][j] + lista[i][j+1] ]
        linha += [1]
        lista += [linha]
    return lista
 
n = input(Nรบmero de lineas para triangulo de Pascal: ")
resultado = trianguloPascal(n)
 
for i in resultado:
    print i

Convert RGB value to hexadecimal value
Input: RGB=[125,200,255]
Output: '0x7dc8ff'

def hexa_value(p):
    r  = p[0]
    g = p[1]
    b = p[2]
    return "0x%02x%02x%02x" % (r, g, b)
>>> RGB = [125,200,255]
>>> hexa_value(RGB)
'0x7dc8ff'

Basic Matrix Operations
Multiplicando Lista por un factor
Way 1: " this technique is called list comprehension"

>>> A = [1,2,3]
>>> [2*x for x in A] #Factor=2
[2, 4, 8]

Way 2: Using a defined function that duplicate a number

>>> def double(p):
    return 2*p
>>> A = [1,2,3]
>>> map(double, A)
[2, 4, 8]

Way 3:

>>> A = [1,2,3]
>>> map(lambda x: 2*x, A) #Factor=2
[2, 4, 8]

Multiply a factor with a double list:
Example: Divide each element of D = [[1,2],[3,4]] by 10.0

>>> D = [[1,2],[3,4]]
>>> [map(lambda x: x/10.0, p) for p in D]
[[0.1, 0.2], [0.3, 0.4]]

Suma de Listas

>>> A = [1,2,4]
>>> B = [5,7,8]
>>> C = [-4,-5,1]
>>> map(sum,zip(A,B)) # A + B
[6, 9, 12]
>>> map(sum,zip(A,B,C)) # A+B+C
[2, 4, 13]

Suma de elementos de una matriz(lista doble)

def sumlist_matrix(M):
    return sum(map(sum,M))
>>> D=[[1, 2], [3, 4],[5,5]]
>>> sumlist_matrix(D)
20

Create a list according to a previous list:

def setArray(source, val):
    return [map(lambda x: val*1.0, p) for p in source]
>>> A = [[1,2],[3,4],[5,6]]
>>> B = setArray(A, 5)
>>> B
[[5.0, 5.0], [5.0, 5.0], [5.0, 5.0]]

Do element-wise math between lists

def domath(function, *matrices):
    return map(lambda x: map(function, zip(*x)), zip(*matrices))
>>> A = [[1,2],[3,4],[5,6]]
>>> B = [[5,5],[5,5],[5,5]]
>>> domath(lambda(x,y): (x*y)/3.0,A,B)
[[1.6666666666666667, 3.3333333333333335], [5.0, 6.666666666666667], [8.333333333333334, 10.0]]
>>> #to do math on a single list. enter the same list variable twice
>>> domath(lambda(x,y): x * 3.0 + 5,B,B)
[[20.0, 20.0], [20.0, 20.0], [20.0, 20.0]]