Friday, September 11, 2015

global variables in python

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print globvar     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

word count using dictionary

counts = {}
for w in words:
    counts[w] = counts.get(w,0) + 1

count letters using dictionary get method

def countLetters(word):
    letterdict = {}
    for letter in word:
        letterdict[letter] = letterdict.get(letter, 0) + 1
    return letterdict

Find duplicates and store them in list

a= [1,2,3,2,1,5,6,5,5,5]
d = {}
for elem in a:
    if elem in d:
        d[elem] += 1
    else:
        d[elem] = 1

print d

print directory contents

import os

def file_list(dir):
    basedir = dir
    subdir_list = []
    for item in os.listdir(dir):
        fullpath = os.path.join(basedir,item)
        if os.path.isdir(fullpath):
            subdir_list.append(fullpath)
        else:
            print fullpath

    for d in subdir_list:
        file_list(d)

file_list('/dir')

Bubble sort in Python

def bubble_sort(items): """ Implementation of bubble sort """ for i in range(len(items)): for j in range(len(items)-1-i): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j]

Exceptions: try,catch and finally in Python

# A finally block is ALWAYS run, even if you return before it

def getkids():
        try:
                val = int(raw_input("how many kids have you? "))
        except StandardError, e:
                print "Error - ",e
                return "yer wot?"
        finally:
                print "T time"
        print val
        return val

getkids()
getkids()
getkids()

Thursday, September 10, 2015

Logging Module in Python

import logging
 
logging.basicConfig(filename="sample.log", level=logging.INFO)
log = logging.getLogger("ex")
 
try:
    raise RuntimeError
except Exception, err:
    log.exception("Error!")
 
 
You can find a good blog on Logging here:
 
http://www.blog.pythonlibrary.org/2012/08/02/python-101-an-intro-to-logging/ 

Sets in python

a = set(["Jake", "John", "Eric"])
b=set(["asas","sdsad","Eric"])

print a.intersection(b)
print a.difference(b)
print a.union(b)

lamda example in python

def mysqr(x):
lambda x : x ** 2
items=[324,324,324,324,324,324,324,32,432,4324]
print list(map(mysqr,items)

Simple demonstration of *argc

def sumall(*argc):
    sum=0
    for i in argc:
        sum=sum + i
    return sum
   
print sumall(1,2,3)

Reduce,Map and Filter examples in the most simplest way

Map:

def to_gram(K):
    return (K * 1000)

def to_kilogram(G):
    return G/1000
   
grams=[5000,6000,7000]
kilograms=[1,2,3]

G=map(to_gram,kilograms)
K=map(to_gram,grams)

print "Grams ""+ G
print "Kgs" + K

Filter:
def div_by_2(x):
    return x % 2 == 0

arr = [1, 2, 3, 4]
new_arr = filter(div_by_2, arr)
new_arr will contain [2, 4]

reduce:

def add_arr(x, y):
    return x + y

arr = [1, 2, 3]

sum = reduce(add_arr, arr)