Jun 24, 2018

Python Commad line arguments

#!/usr/local/bin/python2.7

'''
    File name: python_command_line.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

import sys

def multiply_function(val1, val2):
    return_val = 0
    if val1 and val2:
        return_val = val1 * val2
    return return_val


if __name__ == '__main__':
    program_name = sys.argv[0]
    arguments = sys.argv[1:]
    count = len(arguments)
    if count == 2:
        print multiply_function(sys.argv[1], sys.argv[1])
    else:
        print 'Please pass two arguments like "python python_command_line.py 10 20"'

Python Variables Scope

#!/usr/local/bin/python2.7

'''
    File name: python_scope.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
The scope of a variable refers to the places that you can see or access a variable.
If you define a variable at the top level of your script or module, this is a global variable
Module/global scope is a read-only shadow within the local function/method scope:
You can access it, providing there's nothing declared with the same name in local scope, but you can't change it.
'''

variable = 100
variable_new = 1111

def func_with_global_access():
    global variable
    print('variable inside function is : ', variable) #100
    variable = 200
    variable_new = 2222 #Local
    print('variable inside function - changed to : ', variable) #200
    print('variable_new inside function - changed to : ', variable_new) #2222

def func_without_global_access():
    try:
        print('variable_new inside fucntion - changed to : ', variable_new) #1111
        variable_new += 100
        """
        #Local variable 'variable_new' referenced before assignment
        #This is because module/global scope is a read-only shadow within the local function/method scope:
        #You can access it, providing there's nothing declared with the same name in local scope,
        #but you can't change it.
        """
        print('variable_new inside fucntion - changed to : ', variable_new) #2222
    except Exception, e:
        print e #local variable 'variable_new' referenced before assignment

print '----------------Global variable----------------------'
print ('variable outside is : ', variable) #100
func_with_global_access()
print ('variable outside is : ', variable) #200
print ('variable_new outside is : : ', variable_new) #1111

print '----------------Local variable----------------------'
print ('variable_new outside is : ', variable_new) #1111
func_without_global_access()
print ('variable_new outside is : ', variable_new) #1111


Python Functions

#!/usr/local/bin/python2.7

'''
    File name: functions_python.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
Functions are meant to re-use & reduce repeated code
Python functions are passed by reference by default
Non-default argument should never follows default argument
ie.,
    def getEvenOddNumbers(type="even", list): #Wrong
    def getEvenOddNumbers(list, type="even", list): Right
Python Fucntons support Default arguments
Anonymous functions
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
Return statements
'''

def getEvenOddNumbers(list=[], type="even"):
    result_list = []
    try:
        if type == 'odd':
            result_list = [i for i in list if i%2 != 0]
        else:
            result_list = [i for i in list if i%2 == 0]
    except Exception, e:
        print '**** Error: ' + str(e)   
    return result_list

def sumUpAll(*kargs):
    print kargs
    return_val = 0
    for each_argument in kargs:
        return_val += each_argument
    return return_val

#Anonymous Fucntion
sum_func = lambda arg1, arg2: arg1 + arg2

#When you run this as a stand alone script, the following will get executed
#When you import this file, the following will not get executed
if __name__ == "__main__":
    localList = [3, 5, 7, 10, 20 , 36, 98, 33, 23, 76]
    print '------------Function - with default args-------------------'
    print  localList
    print getEvenOddNumbers(localList)
    print '------------Function - with default & non - default args-------------------'
    print getEvenOddNumbers(localList, "odd")
    print '------------Function - with non-default args-------------------'
    print getEvenOddNumbers(type="odd", list=localList)
    localList1 = ['Hi', 'Friend', 'lets', 'rock']
    print localList1
    print getEvenOddNumbers(localList1)
    print '------------Function variable arguments-------------------'
    print sumUpAll(10)
    print sumUpAll(10, 20)
    print sumUpAll(10, 20, 30)
    print sumUpAll(10, 20, 30, 40)
    print sumUpAll(10, 20, 30, 40, 50)
    print '------------Anonymous Function-------------------'
    print sum_func(100, 200)
    print sum_func('India', 'is Great')
    print sum_func([10,20], [30,40])


Output:

------------Function - with default args-------------------
[3, 5, 7, 10, 20, 36, 98, 33, 23, 76]
[10, 20, 36, 98, 76]
------------Function - with default & non - default args-------------------
[3, 5, 7, 33, 23]
------------Function - with non-default args-------------------
[3, 5, 7, 33, 23]
['Hi', 'Friend', 'lets', 'rock']
**** Error: not all arguments converted during string formatting
[]
------------Function variable arguments-------------------
(10,)
10
(10, 20)
30
(10, 20, 30)
60
(10, 20, 30, 40)
100
(10, 20, 30, 40, 50)
150
------------Anonymous Function-------------------
300
Indiais Great
[10, 20, 30, 40]
[Finished in 0.2s]

Python regular expressions

import re

print '-----------------regex search/match/compile---------------------'
match = re.search('hello', 'hi hello world')
if match:
    print match.group()
else:
    print 're.search not found'

match = re.match('hello', 'hi hello world')
if match:
    print match.group()
else:
    print 're.match not found'

match = re.compile('hello').match('hello world')
if match:
    print match.group()  #hello
else:
    print 're.compile not found'

print '-----------------regex search---------------------'
#Case Insensitive Search
str = "Mother Teresa"
print("Input sting : " +  str);
match = re.search(r"mother", str, re.IGNORECASE)  #Case Insensitive Search
if (match):
    print("Matched string : " +  match.group())   
#Matched string : Mother
else:
    print("NOT Matched");   


print '-----------------regex findall in a string---------------------'
str1 = 'Send upport related queries to support@organization.com, send admin related queries to admin@organization.com'
emails = re.findall(r'[\w\.-]+@[\w\.-]+', str1)
for email in emails:
    print email

Output:
support@organization.com
admin@organization.com   

print '-----------------regex findall in file---------------------'
f = open('regex.txt', 'r')
strings = re.findall(r'Python', f.read())
for string in strings:
    print('Each String : ', string)

Output:
('Each String : ', 'Python')
('Each String : ', 'Python')
('Each String : ', 'Python')
('Each String : ', 'Python')

print '-----------------regex groups---------------------'
str = "alice@gmail.com"
match = re.match(r'([\w.-]+)@([\w.-]+)', str)
if match:
    print('Match found: ', match.group())
    print('Match found: ', match.group(1))
    print('Match found: ', match.group(2))
else:
    print('No match')

Output:

('Match found: ', 'alice@gmail.com')
('Match found: ', 'alice')
('Match found: ', 'gmail.com')

print '-----------------regex compile---------------------'
# Case Insensitive Search using compile
# Compile is more useful in loops & iterations, this will avoid re-building regex everytime
str = "Mother Teresa"
print("\n Input Str : ", str)
match = re.compile(r"mother ", re.IGNORECASE)  #Case Insensitive Search
if (match.search(str)):
    print("Matched Str")
else:
    print("NOT Matched Str")



Output:

-----------------regex search/match/compile---------------------
hello
re.match not found
hello
-----------------regex search---------------------
Input sting : Mother Teresa
Matched string : Mother
-----------------regex findall in a string---------------------
support@organization.com
admin@organization.com
-----------------regex findall in file---------------------
('Each String : ', 'Python')
('Each String : ', 'Python')
('Each String : ', 'Python')
('Each String : ', 'Python')
-----------------regex groups---------------------
('Match found: ', 'alice@gmail.com')
('Match found: ', 'alice')
('Match found: ', 'gmail.com')
-----------------regex compile---------------------
('\n Input Str : ', 'Mother Teresa')
Matched Str

Read direcory in Python

'''
    File name: dir_read.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

import glob
import os

rootdir = 'Exercise'

print '------------glob------------------'
#List only python files
glob_root_dir = os.path.join(rootdir, '*.py')
arr_list = glob.glob(glob_root_dir)
for each_file in arr_list:
    print(each_file)

print '------------listdir------------------'
#List only txt files
for each_file in os.listdir(rootdir):
    file_path = os.path.join(rootdir,each_file)
    file_base, extension = os.path.splitext(file_path)
    #print extension
    if os.path.isfile(file_path) and extension == '.txt':
        print each_file
print '######'
for each_file in os.listdir(rootdir):
    print(each_file)

print '------------os.walk------------------'
for root, dirs, files in os.walk(rootdir):
    print '---Each loop'
    print root
    if dirs:
        print '###### Dirs'
        for file in dirs:
            print os.path.join(root, file)
    print '###### Files'
    for file in files:
        print os.path.join(root, file)

Jun 23, 2018

Learning For While loops in Python

#!/usr/local/bin/python2.7

'''
    Learning For/While loops in Python
    File name: for_while_loop_python.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
Topics:
For loop
While loop
range
break
continue
enumerate
'''

print '----------------For loop---------------------'
freedom_fighters = ["Lala Lajipati Rai", "Dadabhai Naoroji", "Rajendra Prasad", "Sarojini Naidu", "Dadabhai Naoroji", "Lal Bahadur Shastri"]
print freedom_fighters
for each in freedom_fighters:
print each

print '----------------For loop Break---------------------'
print freedom_fighters
#Print only first 4 elements using Break statement
#Enumerate will get you index of the element as well - starting from 0
#enumerate(freedom_fighters) will start the index from 0
#enumerate(freedom_fighters, 1) will start the index from 1
for index,each in enumerate(freedom_fighters, 1):
print index, each
if index == 4:
break
print '----------------For loop Continue---------------------'
print freedom_fighters
#Print only even elements from the list
for index,each in enumerate(freedom_fighters, 1):
if index % 2 == 1: #Odd elements
continue
else: #Even Elements
print index, each

print '----------------For loop Range---------------' 
squares = []
print range(1,10)
for x in range(0,10):
squares.append(x**2)
print (squares)

print '----------------While loop---------------'
#Try to avoild While loops, use only unless otherwise reequired
#If you sometimes don't handle it, it may end up in infinite loop
i = 0
squares = []
while(i < 10):
squares.append(i**2)
i += 1
print squares

Output:

----------------For loop---------------------
['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
Lala Lajipati Rai
Dadabhai Naoroji
Rajendra Prasad
Sarojini Naidu
Dadabhai Naoroji
Lal Bahadur Shastri
----------------For loop Break---------------------
['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
1 Lala Lajipati Rai
2 Dadabhai Naoroji
3 Rajendra Prasad
4 Sarojini Naidu
----------------For loop Continue---------------------
['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
2 Dadabhai Naoroji
4 Sarojini Naidu
6 Lal Bahadur Shastri
----------------For loop Range---------------
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
----------------While loop---------------
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[Finished in 0.2s]

Learning Strings in Python

#!/usr/local/bin/python2.7

'''
#Learning Strings in Python
    File name: string_all_operations.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
Python Strings are immutable
Python uses single quotes ' double quotes " and triple quotes """
['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
'''

string = "india also called the Republic of India is a country in South Asia. India is the seventh-largest country by area, the second-most populous country (with over 1.2 billion people), and the most populous democracy in the world."
print string

#The capitalize() function returns a string with the first character in capital.
#Immutable
string_cap = string.capitalize()
print string_cap
print string

print '---------------Slice---------------'
print string[0:20]
print string[-5:]

#india also called th
#orld.

print '---------------Forming String with variables---------------'
print "The item {} is repeated {} times".format('test',100)
#The item test is repeated 100 times

print "The item %s is repeated %d times"% ('test',100)
#The item test is repeated 100 times

# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
#Hello Adam, your balance is 230.2346.

# positional arguments
print("Hello {0}, your balance is {2}.".format("Adam", 230.2346, 100))
#Hello Adam, your balance is 230.2346.

# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))
#Hello Adam, your balance is 230.2346.

# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))
#Hello Adam, your balance is 230.2346.

#print("{:2.2f}".format(234567.2346768778))
print("{:.3f}".format(12.2346768778))
#12.235

print '---------------check if Substring Exists---------------'
print 'democracy' in string
#True

print '---------------String Copy---------------'
string_1 = string
string_1 += ' India is great'
print string
print string_1
#india also called the Republic of India is a country in South Asia. India is the seventh-largest country by area, the second-most populous country (with over 1.2 billion people), and the most populous democracy in the world.
#india also called the Republic of India is a country in South Asia. India is the seventh-largest country by area, the second-most populous country (with over 1.2 billion people), and the most populous democracy in the world. India is great

print '---------------String Upper/Lower Case---------------'
print string_1.upper()
print string_1.lower()

#INDIA ALSO CALLED THE REPUBLIC OF INDIA IS A COUNTRY IN SOUTH ASIA. INDIA IS THE SEVENTH-LARGEST COUNTRY BY AREA, THE SECOND-MOST POPULOUS COUNTRY (WITH OVER 1.2 BILLION PEOPLE), AND THE MOST POPULOUS DEMOCRACY IN THE WORLD. INDIA IS GREAT
#india also called the republic of india is a country in south asia. india is the seventh-largest country by area, the second-most populous country (with over 1.2 billion people), and the most populous democracy in the world. india is great

print '---------------String Strip---------------'
string_2 = '   India is a democratic country       '
print string_2
string_2 =  string_2.strip()
print string_2

#   India is a democratic country       
#India is a democratic country

print '---------------String Split---------------'
print string
lista = string.split('country')
print lista

#india also called the Republic of India is a country in South Asia. India is the seventh-largest country by area, the second-most populous country (with over 1.2 billion people), and the most populous democracy in the world.
#['india also called the Republic of India is a ', ' in South Asia. India is the seventh-largest ', ' by area, the second-most populous ', ' (with over 1.2 billion people), and the most populous democracy in the world.']

print '---------------String Join---------------'
print lista
print "," .join(lista)
#print string

#['india also called the Republic of India is a ', ' in South Asia. India is the seventh-largest ', ' by area, the second-most populous ', ' (with over 1.2 billion people), and the most populous democracy in the world.']
#india also called the Republic of India is a , in South Asia. India is the seventh-largest , by area, the second-most populous , (with over 1.2 billion people), and the most populous democracy in the world.

print '---------------String Title---------------'
print string.title()
#India Also Called The Republic Of India Is A Country In South Asia. India Is The Seventh-Largest Country By Area, The Second-Most Populous Country (With Over 1.2 Billion People), And The Most Populous Democracy In The World.

print '---------------String find---------------'
print string
print string.find('country') #returns lowest index
print string.rfind('republic') #returns highest index, if not found, retunns -1
#india also called the Republic of India is a country in South Asia. India is the seventh-largest country by area, the second-most populous country (with over 1.2 billion people), and the most populous democracy in the world.
#45
#-1

print '---------------String functions---------------'
print string.capitalize()
#India also called the republic of india is a country in south asia. india is the seventh-largest country by area, the second-most populous country (with over 1.2 billion people), and the most populous democracy in the world.

print string.count('country') #No of times subsrting has repeated
#3

print string.isspace() #returns true if there are only whitespace characters
#False

string_2 = string.swapcase()
print string_2
#INDIA ALSO CALLED THE rEPUBLIC OF iNDIA IS A COUNTRY IN sOUTH aSIA. iNDIA IS THE SEVENTH-LARGEST COUNTRY BY AREA, THE SECOND-MOST POPULOUS COUNTRY (WITH OVER 1.2 BILLION PEOPLE), AND THE MOST POPULOUS DEMOCRACY IN THE WORLD.

print string_2.swapcase()
#india also called the Republic of India is a country in South Asia. India is the seventh-largest country by area, the second-most populous country (with over 1.2 billion people), and the most populous democracy in the world.

print string.center(250, '-')
#-------------india also called the Republic of India is a country in South Asia. India is the seventh-largest country by area, the second-most populous country (with over 1.2 billion people), and the most populous democracy in the world.-------------

Learning Dictionary in Python

#!/usr/local/bin/python2.7

'''
#Learning Dictionary in Python
    File name: dict_all_operations.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
Python Dictionaries has key value pairs
They are not ordered
They don't have any index
Keys are unique
A key can be any type of objects, for example, a number, string in Python dictionary
Values can be accessed by using key rather than the index 
We can fetch the values by using key
Case sensitive

[ 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
'''
from copy import deepcopy
import operator

employees = {1000: {'name': 'Sahasra','country': 'India', 'age': 25}, \
1001: {'name': 'Peter','country': 'US', 'age': 21}, \
1002: {'name': 'John','country': 'US', 'age': 36}, \
1003: {'name': 'Sarayu','country': 'India', 'age': 30},\
1004: {'name': 'Akio','country': 'Japan', 'age': 60}, \
1005: {'name': 'Anand','country': 'India', 'age': 50}, \
1006: {'name': 'Vidya','country': 'India', 'age': 32}, \
1007: {'name': 'Salma','country': 'Bangladesh', 'age': 23},}
print employees

#{1000: {'country': 'India', 'age': 25, 'name': 'Sahasra'}, 1001: {'country': 'US', 'age': 21, 'name': 'Peter'}, 1002: {'country': 'US', 'age': 36, 'name': 'John'}, 1003: {'country': 'India', 'age': 30, 'name': 'Sarayu'}, 1004: {'country': 'Japan', 'age': 60, 'name': 'Akio'}, 1005: {'country': 'India', 'age': 50, 'name': 'Anand'}, 1006: {'country': 'India', 'age': 32, 'name': 'Vidya'}, 1007: {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}}

print '---------------Dictionary Keys---------------'
print employees.keys() #Get employee Ids
#[1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

print '---------------Dictionary Values---------------'
print employees.values()
#[{'country': 'India', 'age': 25, 'name': 'Sahasra'}, {'country': 'US', 'age': 21, 'name': 'Peter'}, {'country': 'US', 'age': 36, 'name': 'John'}, {'country': 'India', 'age': 30, 'name': 'Sarayu'}, {'country': 'Japan', 'age': 60, 'name': 'Akio'}, {'country': 'India', 'age': 50, 'name': 'Anand'}, {'country': 'India', 'age': 32, 'name': 'Vidya'}, {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}]

print '---------------Dictionary Access---------------'
print employees[1002]
#{'country': 'US', 'age': 36, 'name': 'John'}
employee_obj = employees[1002]
print employee_obj['name']
#John
print employee_obj['country']
#US
print employee_obj['age']
#36
#print employee_obj['salary'] #This will throw error
print employee_obj.get('salary') #Get will return None atleast, but won't throw any error

print '---------------Dictionary Check if key exists---------------'
print 1002 in employees
#True
print 2002 in employees.keys()
#False
print employees.has_key('dept')
#None

print '---------------Dictionary Add/update---------------'
print employees
employees[1008] = {'name': 'Sriya','country': 'India', 'age': 42}

print employees.keys()
#[1008, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

employees.update({1009: {'name': 'Ahmad','country': 'Bangladesh', 'age': 60}})
print employees.keys()
#[1008, 1009, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

print '---------------Dictionary Delete entry---------------'
print employees.keys()
#[1008, 1009, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

del employees[1009]

print employees.keys()
#[1008, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007]

print employees[1002]
#{'country': 'US', 'age': 36, 'name': 'John'}

del employees[1002]['age']

print employees[1002]
#{'country': 'US', 'name': 'John'}

print employees[1002].pop('country') #You need to specify key name
#US

print employees[1002]
#{'name': 'John'}

print '---'
print employees[1002].popitem() #It randomly removed any one key
#('name', 'John')

print '---'
print employees[1002]
#{}

print '---'
print len(employees)
#9
del employees[1002]

print len(employees)
#8

print '---------------Dictionary copy by ref---------------'
print employees[1008]['age']
employees_1 = employees
employees[1008]['age'] = 45
print employees[1008]['age']
print employees_1[1008]['age']
#42
#45
#45

print '---------------Dictionary shallow copy---------------'
print employees[1008]['age']
employees_1 = employees.copy()
employees[1008]['age'] = 50
print employees[1008]['age']
print employees_1[1008]['age']
#45
#50
#50

print '---------------Dictionary deep copy---------------'
print employees[1008]['age']
employees_1 = deepcopy(employees)
employees[1008]['age'] = 55
print employees[1008]['age']
print employees_1[1008]['age']
#50
#55
#50

print '---------------Dictionary loop---------------'
for key,val in employees.items():
    print key, ' ----> ', val
for key in employees:
    print key, ' ----> ', employees[key]

#1008  ---->  {'country': 'India', 'age': 55, 'name': 'Sriya'}
#1000  ---->  {'country': 'India', 'age': 25, 'name': 'Sahasra'}
#1001  ---->  {'country': 'US', 'age': 21, 'name': 'Peter'}
#1003  ---->  {'country': 'India', 'age': 30, 'name': 'Sarayu'}
#1004  ---->  {'country': 'Japan', 'age': 60, 'name': 'Akio'}
#1005  ---->  {'country': 'India', 'age': 50, 'name': 'Anand'}
#1006  ---->  {'country': 'India', 'age': 32, 'name': 'Vidya'}
#1007  ---->  {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}


print '---------------Dictionary sort by key---------------'
for key in sorted(employees):
    print key, ' ----> ', employees[key]

#1000  ---->  {'country': 'India', 'age': 25, 'name': 'Sahasra'}
#1001  ---->  {'country': 'US', 'age': 21, 'name': 'Peter'}
#1003  ---->  {'country': 'India', 'age': 30, 'name': 'Sarayu'}
#1004  ---->  {'country': 'Japan', 'age': 60, 'name': 'Akio'}
#1005  ---->  {'country': 'India', 'age': 50, 'name': 'Anand'}
#1006  ---->  {'country': 'India', 'age': 32, 'name': 'Vidya'}
#1007  ---->  {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}
#1008  ---->  {'country': 'India', 'age': 55, 'name': 'Sriya'}

print '---------------Dictionary sort by value ---------------'
try:
   #Dictionary of Dictionaries - sort of specific value    
   print sorted(employees.items(), key=lambda(x,y): y['age'])
   #[(1001, {'country': 'US', 'age': 21, 'name': 'Peter'}), (1007, {'country': 'Bangladesh', 'age': 23, 'name': 'Salma'}), (1000, {'country': 'India', 'age': 25, 'name': 'Sahasra'}), (1003, {'country': 'India', 'age': 30, 'name': 'Sarayu'}), (1006, {'country': 'India', 'age': 32, 'name': 'Vidya'}), (1005, {'country': 'India', 'age': 50, 'name': 'Anand'}), (1008, {'country': 'India', 'age': 55, 'name': 'Sriya'}), (1004, {'country': 'Japan', 'age': 60, 'name': 'Akio'})]

   #Based on Value
   x = {1: 2000, 3: 8000, 4: 2500, 2: 9000, 9:10000, 7:9500}
   print x
   #{1: 2000, 2: 9000, 3: 8000, 4: 2500, 7: 9500, 9: 10000}

   sorted_x = sorted(x.items(), key=operator.itemgetter(1))
   print sorted_x
   #[(1, 2000), (4, 2500), (3, 8000), (2, 9000), (7, 9500), (9, 10000)]

   sorted_x = sorted(x.items(), key=lambda(x,y): y)
   print sorted_x
   #[(1, 2000), (4, 2500), (3, 8000), (2, 9000), (7, 9500), (9, 10000)]
except Exception, e:
   print e    



Jun 22, 2018

Learning Tuples in Python

#!/usr/local/bin/python2.7

'''
#Learning Tuples
    File name: tuple_all_operations.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
Tuples are immutable,means not changable
Tuples have no append or extend method.
Elements in Tuples cannot be removed from a tuple.
You can only find elements in a tuple, since this doesn not change the tuple.
You can also use the in operator to check if an element exists in the tuple.
Tuples are faster than lists. If you have a constant set of values, use a tuple instead of a list.
It makes your code safer if you 'write-protect' data that does not need to be changed.
'''

freedom_fighters = ("Lala Lajipati Rai", "Dadabhai Naoroji", "Rajendra Prasad", "Sarojini Naidu", "Dadabhai Naoroji", "Lal Bahadur Shastri")
print freedom_fighters
#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')

print '---------------index---------------'
print freedom_fighters[0]
print freedom_fighters[-1]
print freedom_fighters[2:]
print freedom_fighters[:-1]
print freedom_fighters[2:4]

#Lala Lajipati Rai
#Lal Bahadur Shastri
#('Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')
#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji')
#('Rajendra Prasad', 'Sarojini Naidu')

print '---------------copy---------------'
print freedom_fighters
freedom_fighters_1 = freedom_fighters
freedom_fighters_1 += ("Bhagat Singh",)
print freedom_fighters
print freedom_fighters_1

#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')
#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')
#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri', 'Bhagat Singh')

print '---------------List Comprehension ---------------'
print [i + ' India saluets you' for i in freedom_fighters]
genrator_obj = (i + ' India saluets you' for i in freedom_fighters)
print genrator_obj
for each in genrator_obj:
print each

#['Lala Lajipati Rai India saluets you', 'Dadabhai Naoroji India saluets you', 'Rajendra Prasad India saluets you', 'Sarojini Naidu India saluets you', 'Dadabhai Naoroji India saluets you', 'Lal Bahadur Shastri India saluets you']
#<generator object <genexpr> at 0x0000000001DC41B0>
#Lala Lajipati Rai India saluets you
#Dadabhai Naoroji India saluets you
#Rajendra Prasad India saluets you
#Sarojini Naidu India saluets you
#Dadabhai Naoroji India saluets you
#Lal Bahadur Shastri India saluets you

print '---------------multiply---------------'
freedom_fighters2 = freedom_fighters * 2
print freedom_fighters2
#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri', 'Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')

print '---------------check if item exits---------------'
print freedom_fighters
print 'Bhagat Singh' in freedom_fighters
print 'Sarojini Naidu' in freedom_fighters

#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')
#False
#True

print '---------------Remove Duplicates---------------'
freedom_fighters3 = freedom_fighters * 2
print freedom_fighters3
#print set(freedom_fighters3)
freedom_fighters_no_dup =[]
[freedom_fighters_no_dup.append(x) for x in freedom_fighters if x not in freedom_fighters_no_dup]
print tuple(freedom_fighters_no_dup)
print tuple(set(freedom_fighters3)) #set - unordered collection data type, this kills the original order

#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri', 'Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')
#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Lal Bahadur Shastri')
#('Rajendra Prasad', 'Sarojini Naidu', 'Lala Lajipati Rai', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')


print '---------------Convert to list---------------'
print freedom_fighters
print list(freedom_fighters)
print tuple(list(freedom_fighters))

#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')
#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')

print '---------------length of array---------------'
print freedom_fighters
print len(freedom_fighters)

#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')
#6

print '---------------Default multile values assingn---------------'
#Python Default assigns to tuple
freedom_fighters_2 = 'Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Lala Lajipati Rai'
print freedom_fighters_2
print type(freedom_fighters_2)

#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Lala Lajipati Rai')
#<type 'tuple'>

print '---------------Default multile values assingn---------------'
print freedom_fighters
print freedom_fighters.count('Lala Lajipati Rai')
freedom_fighters += ('Lala Lajipati Rai',)
print freedom_fighters.index('Sarojini Naidu')
print freedom_fighters
print freedom_fighters.count('Lala Lajipati Rai')

#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri')
#1
#3
#('Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri', 'Lala Lajipati Rai')
#2




Html5 - How to disable video download

Html5 - How disable video download

  • Use controls controlsList="nodownload" to disable download
  • Use oncontextmenu="return false;" to avoid right click and they by avoid save as option

Sample Snippet

<video width="512" height="380" controls controlsList="nodownload" oncontextmenu="return false;">
    <source data-src="mov_bbb.ogg" type="video/mp4">
</video>

Learning lists - all operations

#!/usr/local/bin/python2.7

'''
    File name: list_all_operations.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

freedom_fighters = ["Lala Lajipati Rai", "Dadabhai Naoroji", "Rajendra Prasad", "Sarojini Naidu", "Dadabhai Naoroji", "Lal Bahadur Shastri"]
print freedom_fighters
#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']

print '---------------index---------------'
print freedom_fighters[0]
print freedom_fighters[-1]
print freedom_fighters[2:]
print freedom_fighters[:-1]
print freedom_fighters[2:4]

#Lala Lajipati Rai
#Lal Bahadur Shastri
#['Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji']
#['Rajendra Prasad', 'Sarojini Naidu']

print '---------------insert in index---------------'
freedom_fighters[2] = 'Subhash Chandra Bose'
print freedom_fighters
#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Subhash Chandra Bose', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']

print '---------------Add Element append vs extend---------------'
print freedom_fighters
#Append - appends as a single item
freedom_fighters.append('Subhash Chandra Bose')
print freedom_fighters
freedom_fighters.pop()
freedom_fighters.append(['Subhash Chandra Bose', 'Lal Bahadur Shastri'])
print freedom_fighters
freedom_fighters.pop()
#Extend - it adds multiple values
freedom_fighters.extend(['Subhash Chandra Bose', 'Lal Bahadur Shastri'])
print freedom_fighters
freedom_fighters.pop()
freedom_fighters.pop()
print freedom_fighters

#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Subhash Chandra Bose', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Subhash Chandra Bose', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri', 'Subhash Chandra Bose', ['Subhash Chandra Bose', 'Lal Bahadur Shastri']]
#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Subhash Chandra Bose', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri', 'Subhash Chandra Bose', 'Subhash Chandra Bose', 'Lal Bahadur Shastri']
#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Subhash Chandra Bose', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']

print '---------------Remove Element by value---------------'
print freedom_fighters
freedom_fighters.remove('Subhash Chandra Bose')
print freedom_fighters

#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Subhash Chandra Bose', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']

print '-----------delete by index---------------------'
print freedom_fighters
del freedom_fighters[-1] #removes index element
del freedom_fighters[1] #removes index element
print freedom_fighters

#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
#['Lala Lajipati Rai', 'Sarojini Naidu', 'Dadabhai Naoroji']

print '---------------By Ref---------------'
print freedom_fighters

#copy by Reference
freedom_fighters_1 = freedom_fighters
freedom_fighters_1.append('Bhagat Singh')
print freedom_fighters
print freedom_fighters_1

#['Lala Lajipati Rai', 'Sarojini Naidu', 'Dadabhai Naoroji']
#['Lala Lajipati Rai', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Bhagat Singh']
#['Lala Lajipati Rai', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Bhagat Singh']

print '---------------By Value -----------'
#copy by value
freedom_fighters_2 = freedom_fighters[:]
freedom_fighters_2.append('Sardar Vallabhbhai Patel')
print freedom_fighters
print freedom_fighters_2

#['Lala Lajipati Rai', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Bhagat Singh']
#['Lala Lajipati Rai', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Bhagat Singh', 'Sardar Vallabhbhai Patel']

print '---------------List Comprehension ---------------'

#This gives list
print [i + ' - India Salutes you' for i in freedom_fighters]

#tuple - gives generator object
generator_obj = (i + ' - India Salutes you' for i in freedom_fighters)
print generator_obj
for each in generator_obj:
print each

#['Lala Lajipati Rai - India Salutes you', 'Sarojini Naidu - India Salutes you', 'Dadabhai Naoroji - India Salutes you', 'Bhagat Singh - India Salutes you']
#<generator object <genexpr> at 0x0000000001EB41B0>
#Lala Lajipati Rai - India Salutes you
#Sarojini Naidu - India Salutes you
#Dadabhai Naoroji - India Salutes you
#Bhagat Singh - India Salutes you

print '---------------Sorted()---------------'
print freedom_fighters
print sorted(freedom_fighters)
print freedom_fighters

#['Lala Lajipati Rai', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Bhagat Singh']
#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu']
#['Lala Lajipati Rai', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Bhagat Singh']

print '---------------list.reverse() ---------------'
print freedom_fighters
print freedom_fighters.reverse() #Returns None but reverse itself
print freedom_fighters

#['Lala Lajipati Rai', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Bhagat Singh']
#None
#['Bhagat Singh', 'Dadabhai Naoroji', 'Sarojini Naidu', 'Lala Lajipati Rai']

print '---------------list.sort() ---------------'
print freedom_fighters
print freedom_fighters.sort() #Returns None but sorts itself
print freedom_fighters

#['Bhagat Singh', 'Dadabhai Naoroji', 'Sarojini Naidu', 'Lala Lajipati Rai']
#None
#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu']

print '---------------multiply---------------'
freedom_fighters2 = freedom_fighters * 2
print freedom_fighters2
#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu']

print '---------------check if item exits---------------'
print freedom_fighters
print 'Bhagat Singh' in freedom_fighters
print 'Sardar Vallabhbhai Patel' in freedom_fighters

#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu']
#True
#False

print '---------------Remove Duplicates---------------'
print freedom_fighters
freedom_fighters.append('Mahatma Gandhi')
freedom_fighters.append('Mahatma Gandhi')
print freedom_fighters
freedom_fighters_no_dup = []
[freedom_fighters_no_dup.append(x) for x in freedom_fighters if x not in freedom_fighters_no_dup]
print freedom_fighters_no_dup
print list(set(freedom_fighters)) #set - unordered collection data type, this kills the original order

#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu']
#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi']
#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi']
#['Mahatma Gandhi', 'Bhagat Singh', 'Lala Lajipati Rai', 'Dadabhai Naoroji', 'Sarojini Naidu']

print '---------------Convert to tuple---------------'
print freedom_fighters
print tuple(freedom_fighters)
print list(tuple(freedom_fighters))

#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi']
#('Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi')
#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi']

print '---------------length of array---------------'
print freedom_fighters
print len(freedom_fighters) 

#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi']
#6

print '---------------Find count of Element---------------'
freedom_fighters.append('Bhagat Singh')
print freedom_fighters
print freedom_fighters.count('Bhagat Singh')

#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi', 'Bhagat Singh']
#2

print '---------------Pop---------------'
#pop() method removes and returns the last item if index is not provided
print freedom_fighters
freedom_fighters.pop()
print freedom_fighters

#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi', 'Bhagat Singh']
#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi']

print '---------------Insert---------------'
#When you insert(-3, 0) you are inserting 0 before index -3. 
#When it says "before" it has nothing to do with the direction of travel.
print freedom_fighters
freedom_fighters.insert(0,'Sarojini Naidu')
freedom_fighters.insert(len(freedom_fighters),'Sarojini Naidu')
print freedom_fighters
freedom_fighters.insert(-1,'Bhagat Singh')
print freedom_fighters
del freedom_fighters[0]
freedom_fighters.pop()
freedom_fighters.pop()
print freedom_fighters

#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi']
#['Sarojini Naidu', 'Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi', 'Sarojini Naidu']
#['Sarojini Naidu', 'Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi', 'Bhagat Singh', 'Sarojini Naidu']
#['Bhagat Singh', 'Dadabhai Naoroji', 'Lala Lajipati Rai', 'Sarojini Naidu', 'Mahatma Gandhi', 'Mahatma Gandhi']

print '---------------Other Functions---------------'
#sorted(freedom_fighters)
#print max(freedom_fighters)
#print min(freedom_fighters)
#print sum(list1)