Python itertools example source code



'''
Created on Aug 3, 2013

@author: tunatore
'''

#python itertools examples
#Functions creating iterators for efficient looping
#refer to http://python.readthedocs.org/en/v2.7.2/library/itertools.html

from itertools import *

#count 
#counter starting from 1 to infinite 
for i in count(1):
    print (i, " ",  end="")
    if (i==15):
        break        
#1  2  3  4  5  6  7  8  9  10  11  12  13  14  15 
print ("\n")

#counter starting from 1 (increment with 5) to infinite
for i in count(1,5):
    print (i, " ",  end="")
    if (i>=50):
        break    
#1  6  11  16  21  26  31  36  41  46  51  

print ("\n")

#cycle
c = cycle("TUNA")
for i in range(12):
    print (next(c), end="")

#TUNATUNATUNATUNATUNATUNA

print ("\n")

#repeat
for i in repeat('python', 4):
    print (i, end="")

#pythonpythonpythonpython

#chain
print ("\n")
list1 = ['Test1','Goose','Bison','Pelican']
list2 = ['Cat','Dog','Elephant','Bird','Tiger','Lion','Rabbit']
print ([i for i in chain(list1,list2)],"\n")
#['Test1', 'Goose', 'Bison', 'Pelican', 'Cat', 'Dog', 'Elephant', 'Bird', 'Tiger', 'Lion', 'Rabbit']

#compress
print ([i for i in compress('TUNATORE', [1,1,1,1,False,False,False,0])],"\n")
#['T', 'U', 'N', 'A']
#or
print ([i for i in compress('TUNATORE', [0,0,0,0,1,1,1,1])],"\n")
#['T', 'O', 'R', 'E']

#dropwhile (starts when prediction fails)
print ([i for i in dropwhile(lambda z: z>3, [9,5,6,7,2,1,4,5,6])],"\n")
#[2, 1, 4, 5, 6]

#takewhile (starts when as long as prediction true)
print ([i for i in takewhile(lambda z: z>6, [9,8,7,6,5,4,3,2,1])],"\n")
#[9, 8, 7]

#filterfalse (z>3 false items will return)
print ([i for i in filterfalse(lambda z: z>3, [9,5,6,7,2,1,4,5,6])],"\n")
#[2, 1]
#or
#filterfalse (z>3 false items will return)
print ([i for i in filterfalse(lambda z: z<3, [9,5,6,7,2,1,4,5,6])],"\n")
#[9, 5, 6, 7, 4, 5, 6]

#isslice
print([i for i in islice('tuna',2)],"\n")
#['t', 'u']
print([i for i in islice('tuna',2,3)],"\n")
#['n']
print([i for i in islice('tuna',0,None)],"\n")
#['t', 'u', 'n', 'a']

#zip_longest
print([i for i in zip_longest('tntr','uaoe',fillvalue='')],"\n")
#[('t', 'u'), ('n', 'a'), ('t', 'o'), ('r', 'e')]

#product for cartesian
print([i for i in product('tuna','tore')],"\n")
#[('t', 't'), ('t', 'o'), ('t', 'r'), ('t', 'e'), ('u', 't'), ('u', 'o'), ('u', 'r'), ('u', 'e'), ('n', 't'),
#('n', 'o'), ('n', 'r'), ('n', 'e'), ('a', 't'), ('a', 'o'), ('a', 'r'), ('a', 'e')]

#permutations
print([i for i in permutations('tuna',4)],"\n")
#[('t', 'u', 'n', 'a'), ('t', 'u', 'a', 'n'), ('t', 'n', 'u', 'a'), ('t', 'n', 'a', 'u'), ('t', 'a', 'u', 'n'),
# ('t', 'a', 'n', 'u'), ('u', 't', 'n', 'a'), ('u', 't', 'a', 'n'), ('u', 'n', 't', 'a'), ('u', 'n', 'a', 't'),
#('u', 'a', 't', 'n'), ('u', 'a', 'n', 't'), ('n', 't', 'u', 'a'), ('n', 't', 'a', 'u'), ('n', 'u', 't', 'a'),
#('n', 'u', 'a', 't'), ('n', 'a', 't', 'u'), ('n', 'a', 'u', 't'), ('a', 't', 'u', 'n'), ('a', 't', 'n', 'u'),
#('a', 'u', 't', 'n'), ('a', 'u', 'n', 't'), ('a', 'n', 't', 'u'), ('a', 'n', 'u', 't')]

#groupby
#useful itemgetter import
from operator import itemgetter

salesByDay =  [('20130101', 35), ('20130101', 25) ,('20130102', 35), ('20130101', 40), ('20130103', 66) ,('20130103', 66), ('20130102', 44)]

#keys have to be sorted
sortedSalesByDay = sorted(salesByDay, key=itemgetter(0))
for key, values in groupby(sortedSalesByDay, itemgetter(0)):
    print ("Day:",key)
    for value in values:
        print ("Value ",value[1])

# Day: 20130101
# Value  35
# Value  25
# Value  40
# Day: 20130102
# Value  35
# Value  44
# Day: 20130103
# Value  66
# Value  66

Advertisements

Python decorators example source code


Here you can find an example for Python Decorators
summary of content;

built-in decorators
usage of before and after decorator
modifying returning function

'''
Created on Aug 2, 2013

@author: tunatore
'''

#decorators are similar to Aspect Oriented Programming in JAVA 
#They have the ability to run after or before any function 
#decorators are applied with @character
#you can use built-in decorators such as @staticmethod

class Hello():
    @staticmethod
    def f():
        return "Hello"
    
print (Hello.f())

class HelloInstance():
    def f(self):
        return "Hello from Instance"

#the following won't work    
#print (HelloInstance.f())    
#you should try

hwi = HelloInstance()
print (hwi.f())


class User:
    """User class"""
    id = 1234567890
    name = "tuna"

#CHANINED decorators    
def trace(f):
    def newFunc(): #any def method name is allowed such as new,newFunc or wrapper ..
        print ("tracing..")
        f() 
    return newFunc

def storelastlogin(f):
    def newFunc():
        print ("storing..")
        f()
    return newFunc

@trace
@storelastlogin
def login():    
    print ("user ID: " + str(User().id) + " name: " + User().name)

login()

def beforeAndAfter(f):  
    def newFunc(): 
        print ("before.. is called")
        f() 
        print ("after.. is called")
    return newFunc

@beforeAndAfter
def loginSecond():  
    pass #do nothing
    
loginSecond()
    
#CHANGING LOGIC
def changeFunctionLogic(f):
    def newFunc(*args): #any def method name is allowed such as new,newFunc or wrapper ..
        print ("changing output by multiplying function itself")
        return f(*args) * f(*args) 
    return newFunc

@changeFunctionLogic
def multiplyNumbers(arg1,arg2):
    return arg1 * arg2

print ("Result (2*2) * (2*2) =", multiplyNumbers(2, 2))

output

Hello
Hello from Instance
tracing..
storing..
user ID: 1234567890 name: tuna
before.. is called
after.. is called
changing output by multiplying function itself
Result (2*2) * (2*2) = 16

Python getting user input and time usage



'''
Created on Aug 1, 2013
Python version > 3
@author: tunatore
'''
import time

#before python 3 please use raw_input() function instead
#refer to http://www.python.org/dev/peps/pep-3111/

#starting clock
startTime = time.clock()

stars = input('I will print stars tell me any number :')

#printing stars
for j in range(int(stars)+1):
    print ('*'*(j))

word = input('Tell me a word :')

#printing word
for j in range(int(len(word)+1)):
    print (word[j-1]*(j))

#stopping clock
stopTime = time.clock()

print ("You have been using this program for {0} seconds".format( stopTime - startTime))

Output

I will print stars tell me any number :10

*
**
***
****
*****
******
*******
********
*********
**********
Tell me a word :tuna

t
uu
nnn
aaaa
You have been using this program for 4.22824467283872 seconds

Python lambda usage and simple example


Lambda Example Source Code


'''
Created on Jul 31, 2013

@author: tuna
'''

#lambdas are similar to functions in python with simple syntax
#do define a increment lambda 
#first function example below
def addNumbers(x,y):
    return x+y

print(addNumbers(2, 2))

#output 4
#same thing with short lambda syntax

l = lambda x,y : x+y

print "lambda output ", l(2,2)
#lambda output 4

#another example return abs value
l = lambda x : abs(x)

print "lambda abs output", l(-1999)
#lambda abs output 1999
print "lambda abs output", l(6)
#lambda abs output 6

#filtering list using lambda

numberList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
#filtering numbers greater then 10
print (filter(lambda x: x>10, numberList))
#output [11, 12, 13, 14, 15]

#showing only even numbers
print (filter(lambda x: x%2==0, numberList))
#output [2, 4, 6, 8, 10, 12, 14]

#lambda different syntax
print (lambda x : abs(x))(-100)
#100

#lambda different syntax
print (lambda x,y,z: x*y*z)(3, 4, 5)
#output 60

nameList = ["Tornado","Tuna","Bob"]
for name in nameList:
    print (lambda x: x.startswith('T'))(name)
#True
#True
#False

output

4
lambda output 4
lambda abs output 1999
lambda abs output 6
[11, 12, 13, 14, 15]
[2, 4, 6, 8, 10, 12, 14]
100
60
True
True
False

Python iterating over collection with index


Python interation with index example source code;


listIterationWithIndex = ['Test1','Goose','Bison','Pelican']

#iterate over list with index
for i, withIndex in enumerate(listIterationWithIndex):
    print ("element -- ", i , withIndex)

'''
output
element --  0 Test1
element --  1 Goose
element --  2 Bison
element --  3 Pelican
'''

tuple_ =  ('Cat','Dog','Elephant','Bird','Tiger','Lion',\
           'Rabbit')

#iterate over tuple with index
for i, withIndex in enumerate(tuple_):
    print ("element -- ", i , withIndex)

'''
output
element --  0 Cat
element --  1 Dog
element --  2 Elephant
element --  3 Bird
element --  4 Tiger
element --  5 Lion
element --  6 Rabbit
'''
    
dictionaryAnimalSpeed = {'tiger': 65, 'monkey': 25 ,'bison': 35, 'cheetah': 113 }

#iterate over dictionary with index
for i, withIndex in enumerate(dictionaryAnimalSpeed.keys()):
    print ("element -- ", i , withIndex)

'''
output
element --  0 bison
element --  1 cheetah
element --  2 monkey
element --  3 tiger
'''    
    

Django OperationalError: unable to open database file


tuna@tuna-VirtualBox:~/Desktop/djangoprojects/mysite$ python manage.py syncdb
OperationalError: unable to open database file

if you get this error most probably you have typo inside settings.py file (NAME field), also arrange chmod 777 for sqllite.db file

DATABASES = {

‘default’: {
‘ENGINE’: ‘django.db.backends.sqlite3‘, # Add ‘postgresql_psycopg2’, ‘mysql’, ‘sqlite3’ or ‘oracle’.
‘NAME’: ‘/home/tuna/Desktop/djangodb/sqllite.db’, # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
‘USER’: ”,
‘PASSWORD’: ”,
‘HOST’: ”, # Empty for localhost through domain sockets or ‘127.0.0.1’ for localhost through TCP.
‘PORT’: ”, # Set to empty string for default.
}
}

after that you will see that the tables are created automatically;

tuna@tuna-VirtualBox:~/Desktop/djangoprojects/mysite$ python manage.py syncdb
Creating tables …
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

You just installed Django’s auth system, which means you don’t have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (leave blank to use ‘tuna’): tuna

Python JSON parsing example



#Created on Jul 30, 2013
#@author: tunatore

import json

# you can create a json structure
pythonStructure = { 'JavaLevel':'Expert', 'PythonLevel':"Beginner", 'C#Level':"Good" }

print ("Python Structure = " , pythonStructure)

#dumps will load python structure as json
print ("JSON Converted Structure = ", json.dumps(pythonStructure))
print ("JSON Converted Structure Sorted Keys = " , json.dumps(pythonStructure, sort_keys=True))

#pretty printed JSON
print ("pretty printed JSON \n")
print (json.dumps(pythonStructure, sort_keys=True, indent=5, separators=(',', ' : ')))

#dumps will load json structure as python structure
print ("Python Structure = " , (json.loads(json.dumps(pythonStructure))))

#another python struct conversion

pythonData = dict(
 key1 = "Val 1",
 key2 = "Val 2",
 key3 = "Val 3",
 key4 = 4
)

print ("JSON Converted Structure = ", json.dumps(pythonData,sort_keys=True))
#loading and parsing JSON data from url
import urllib.request
url = "http://carma.org/api/1.1/searchLocations?name=Idaho"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
loadJSON = json.loads(response.read().decode('utf-8'))
print (json.dumps(loadJSON, indent=4, sort_keys=True))

# get carbon JSON item
carbon = loadJSON[0]['carbon']
print ("carbon future" , carbon['future'])
print ("carbon past" , carbon['past'])
print ("carbon present" , carbon['present'])

Output;

Python Structure = {‘PythonLevel’: ‘Beginner’, ‘C#Level’: ‘Good’, ‘JavaLevel’: ‘Expert’}
JSON Converted Structure = {“PythonLevel”: “Beginner”, “C#Level”: “Good”, “JavaLevel”: “Expert”}
JSON Converted Structure Sorted Keys = {“C#Level”: “Good”, “JavaLevel”: “Expert”, “PythonLevel”: “Beginner”}
pretty printed JSON

{
“C#Level” : “Good”,
“JavaLevel” : “Expert”,
“PythonLevel” : “Beginner”
}
Python Structure = {‘PythonLevel’: ‘Beginner’, ‘C#Level’: ‘Good’, ‘JavaLevel’: ‘Expert’}
JSON Converted Structure = {“key1”: “Val 1”, “key2”: “Val 2”, “key3”: “Val 3”, “key4”: 4}
[
{
“carbon”: {
“future”: “2068400.0000”,
“past”: “758970.0000”,
“present”: “838420.0000”
},
“country”: {
“id”: “6252001”,
“name”: “United States”
},
“energy”: {
“future”: “18787000.0000”,
“past”: “10677000.0000”,
“present”: “13059000.0000”
},
“fossil”: {
“future”: “0.2371”,
“past”: “0.1666”,
“present”: “0.1339”
},
“hydro”: {
“future”: “0.5648”,
“past”: “0.7809”,
“present”: “0.7996”
},
“id”: “5596512”,
“intensity”: {
“future”: “110.0000”,
“past”: “71.1000”,
“present”: “64.2000”
},
“name”: “Idaho”,
“nuclear”: {
“future”: “0.0000”,
“past”: “0.0000”,
“present”: “0.0000”
},
“plant_count”: “92”,
“renewable”: {
“future”: “0.1981”,
“past”: “0.0525”,
“present”: “0.0664”
},
“type”: “province”
}
]
carbon future 2068400.0000
carbon past 758970.0000
carbon present 838420.0000