Python Tutorial

Showing posts with label pythonic. Show all posts
Showing posts with label pythonic. Show all posts

Friday, January 17, 2014

Python fancy string formatting

print "1. Life is {} {} {} python".format('very','easy', 'with')
print "2. Life is {0} {1} {2} python".format('very','easy', 'with')

print "3. Life is {1} {0} {2} python".format('very','easy', 'with')
print "4. Life is {1} {0} {t} python".format('very','easy', t='with')
print "5. Life is {0} {t} python".format('very easy', t='with')

for n in range(5, 11):
    print "{0:2d} {1:3d} {2:4d}".format(n, n*n, n*n*n)

d = {"name1":100, "name3":350, "name2":250}
print "6. First: {name1:d}, Second: {name2:d}, Third: {name3:d}".format(**d)

print "zfill pads string on left zeros, it also consider + and - sign"
print '25'.zfill(5)
print '2.5'.zfill(5)
print '-2.5'.zfill(5)
print '2.54234324234'.zfill(5)
print 'ah'.zfill(5)

print "asd".rjust(6, 'R')
print "asd".ljust(6, 'R')

Output:
1. Life is very easy with python
2. Life is very easy with python
3. Life is easy very with python
4. Life is easy very with python
5. Life is very easy with python
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
6. First: 100, Second: 250, Third: 350
zfill pads string on left zeros, it also consider + and - sign
00025
002.5
-02.5
2.54234324234
000ah
RRRasd
asdRRR

Thursday, January 16, 2014

python filter(), map(), reduce() with list

  • filter(function, sequence) : returns sequence for which function(item) is true
  • map(function, sequence): call function(item) for each item and returns a list
  • reduce(function, sequence): returns a single value constructed by calling function on first two items on the sequence, then the result and the next item, and so on.
def f(x):
    return x % 2 == 0
print filter(f, range(1,10))


def square(x):
    return x*x
print map(square, range(1,5))

def add(x, y):
    return x+y
print reduce(add, range(1,10))

Output:
[2, 4, 6, 8]
[1, 4, 9, 16]
45

Tuesday, January 14, 2014

Python array declaration by type

Python provides array declaration of specific types(ex-int, float, char). It is much faster(~10x) than normal array. Lets go to the code.

import array

# integer array declaration
a_int = array.array('i')
a_int.append(5)  # Error a_int.append(5.5)
print a_int[0]
a_int = array.array('i', range(10))
print a_int[7]

# float array declaration
a_float = array.array('f')
a_float.append(10)
print a_float[0]

# character array declaration
a_char = array.array('c')
a_char.append('A')
print a_char[0]

a_char = array.array('c', "python")
print a_char[1]

Output:
5
7
10.0
A
y

Friday, December 20, 2013

python dictionary comprehensions

Python dictionary comprehensions is similar to list comprehension. Lets have some example
import os

# from a directory get each file name as key and file size as value
print {filename: os.path.getsize(filename) for filename in os.listdir(os.getcwd()) }

# initialize from 0-9 key as true
print {n: True for n in range(10)}

Python list comprehensions

Python list comprehensions provide many way to create list.
The comrehensions format is [*transform* *iteration* *filter* ].
Let's have some example.

# read a file line by line check whether or not "word" contains in each line (ignore case)
print [ line.strip("\n").lower() for line in open("a.in") if "word" in line]

# initialize array by square number
print [i**2 for i in range(10)]
# initialize array with tuples 
print [(i,i**2) for i in range(10)]

# initialize array by odd number
print [i for i in range(10) if i%2]

words = ["Life", "is", "very", "easy", "Python"]
# print first character of each word
print [word[0] for word in words]

# make all words to upper case
print [word.upper() for word in words]

# Sum each element of two array
a = [1, 2, 3]
b = [4, 5, 6]
print [a[i]+b[i] for i in range(len(a))]

Monday, December 9, 2013

Python for loop with else clauses


Python for loop with else condition is very interesting feature. This types of feature makes code more readable and pythonic. Lets see an example.

a = [1, 3, 51, 7, 8]
print a
k = 5
for n in a:
    if n%k==0:
        print "Divisible by",k,"found"
        break
else:
    # This line will working if for loop terminate normally
    print "Divisible by",k,"not found"

print
a = [1, 3, 5, 7, 8]
print a
k = 5
for n in a:
    if n%k==0:
        print "Divisible by",k,"found"
        break
else:
    # This line will working if for loop terminate normally
    print "Divisible by",k,"not found"


Output:
[1, 3, 51, 7, 8]
Divisible by 5 not found

[1, 3, 5, 7, 8]
Divisible by 5 found