Python Tutorial

Showing posts with label Code snippet. Show all posts
Showing posts with label Code snippet. Show all posts

Sunday, September 28, 2014

Min, max value and index from list

See also enumerate and operator.itemgetter
import operator
a = [2, 5, 1, 4, 8, 71, 4, 1, 21]
min_i, min_v = min(enumerate(a), key = operator.itemgetter(1))
max_i, max_v = max(enumerate(a), key = operator.itemgetter(1))

print "[Min] index:",min_i,"value:",min_v
print "[Max] index:",max_i,"value:",max_v


Output:
[Min] index: 2 value: 1
[Max] index: 5 value: 71

Python: Absolute difference between successive elements in list


See also abs, zip and islice
from itertools import islice

a = [1, 4 , 2 , 6 , 7, 3]
result = [abs(p-q) for p, q in zip(a, islice(a, 1, None))]

print result

Output:
[3, 2, 4, 1, 4]

Thursday, December 12, 2013

Python case insensitive dictionary

class CaseInsensitiveDict(dict):
    def __setitem__(self, key, value):
        key = key.lower()
        dict.__setitem__(self, key, value)

    def __getitem__(self, key):
        key = key.lower()
        return dict.__getitem__(self, key)

d = CaseInsensitiveDict()
d["Python"] = "Easy"
print d["PYTHON"]
print d["python"]

Output:
Easy
Easy

Saturday, July 13, 2013

Python chain comparison


x = 10

print '5<x<9',5<x<9
print '5<x<11',5<x<11
print '5<x<11<10*x<101',5<x<11<10*x<101
print '10==x<90==9*x',10==x<90==9*x

Output:
5<x<9 False
5<x<11 True
5<x<11<10*x<101 True
10==x<90==9*x True

Python unpacking list, tuples or dictionary as function argument.


def my_func(a, b, c):
    print "a,b,c:",a,b,c

my_func(1,2,3)
my_func( *[1,2,3] ) # unpacking from list
my_func( *(1,2,3) ) # unpacking from tuples
my_func( **{'a':1, 'b':2, 'c':3} ) # unpacking from dictionary

Output:
a,b,c: 1 2 3
a,b,c: 1 2 3
a,b,c: 1 2 3
a,b,c: 1 2 3

Monday, May 6, 2013

Python string title - auto capitalize first character of the word

Python auto capitalize first character of all the word/words in a string.
s1 = "life is very easy with python"
s2 = "python"
print s1
print s1.title()

print s2
print s2.title()

Output:
life is very easy with python
Life Is Very Easy With Python
python
Python

Wednesday, February 20, 2013

Python object-class property

Python object-class property example code
class MyClass(object):
        def __init__(self, first_name, last_name):
                self.first_name = first_name
                self.last_name = last_name
        @property
        def name(self):
                return self.first_name +" "+ self.last_name


myClass = MyClass("Abu", "Zahed")
print myClass.name

Output:

Abu Zahed

date compare - code snippet

import datetime

a = datetime.date(2012,1,31) # YYYY, MM, DD
b = datetime.date(2009,10,31) # YYYY, MM, DD

print a == b
print a > b
print a < b


Output:
False
True
False

Tuesday, February 19, 2013

Python isinstance example

Python check an object instance using isinstance method.

class MyClass(object):
    pass

a = MyClass()
print isinstance(a,MyClass)

a = 5
print isinstance(a,MyClass)


Output:
True
False

Decorator in python

Python decorator example : Validate a function argument using decorator.


All source code available on github
from functools import wraps

def validate(func):
    @wraps(func)
    def wrapper(*args):
        for num in args:
            try:
                int(num)
            except:
                return None
        return func(*args)

    return wrapper

@validate
def add_num(*args):
    total = 0
    for num in args:
        total += num
    return total


print add_num(1,2,3)
print add_num(1,2,"asd")
print add_num(1,2,None)


Output:
6
None
None

Python implement caching - using decorator

Python custom caching using decorator.

All source code available on github

from functools import wraps

def custom_memoize(func):
    cache = {}
    @wraps(func)
    def wrapper(*args):
        if args in cache:
            print "Returning cache data"
            return cache[args]
        # If result not found then call the function
        result = func(*args)
        cache[args] = result
        return result

    return wrapper

@custom_memoize
def add(x,y):
    return x+y

print add(1,2)
print add(2,5)
print add(1,2)
print add(2,5)

Output:
3
7
Returning cache data
3
Returning cache data
7

Monday, February 18, 2013

Code snippet: Array initilize by odd number

a=[i for i in range(0,20) if i%2]
print a

Output:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

File read code snippet



All source code available on github

import sys

def readFile(filename):
    try:
        file = open(filename,'r')
        content = file.read()
        file.close()
        return content
    except IOError:
        print "IOError:",IOError.args[0]
    except :
        print "Unexpected error:",sys.exc_info()[0]
        raise