Say you want to replace the keyword arguments of a fuction with dict object, then do the following:
Sample_Fuction(key1="value1", key2="value2)
Sample_Dict = {"key1":"value1", "key2":"value2"}
Replace kwargs with Dict:
Sample_Function(**Sample_Dict)
Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts
Thursday, July 25, 2019
Thursday, January 3, 2019
Python C Extension
Say we want to create a module named "pal" with a function called "f1" to calculate the sum of all numbers. For example to calculate numbers in 5, it does the following:
1+ (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35
Step 1. Create a file called "palmodule.c" :
#include <Python.h>
static PyObject * pal_f1(PyObject *self, PyObject *args) {
int x;
PyArg_ParseTuple(args, "i", &x);
long sum = 0;
for (int C=1; C<=x; ++C) {
for (int c=1; c<C+1; ++c) {
sum = sum + c;
}
}
return Py_BuildValue("l", sum);
}
static PyMethodDef PalMethods[] = {
{"f1", pal_f1, METH_VARARGS, "To calculate the sum of numbers"},
{NULL, NULL}
};
static struct PyModuleDef palmodule = {
PyModuleDef_HEAD_INIT,
"pal", /* name of module */
"Module with Function f1", /* module documentation*/
-1, /* size of per-interpreter state or -1 if module keeps state in global variables.*/
PalMethods
};
PyMODINIT_FUNC PyInit_pal(void) {
return PyModule_Create(&palmodule);
}
Step 2. Create a file called "setup.py"
from distutils.core import setup, Extension
setup (name='pal', version='1.0', ext_modules=[Extension('pal', ['palmodule.c'])])
Step 3. Install the extension using the following command:
sudo python3 setup.py install
Step 4. Now open the python3 interpreter and do the following:
>>> from pal import f1
>>> f1(5)
35
1+ (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35
Step 1. Create a file called "palmodule.c" :
#include <Python.h>
static PyObject * pal_f1(PyObject *self, PyObject *args) {
int x;
PyArg_ParseTuple(args, "i", &x);
long sum = 0;
for (int C=1; C<=x; ++C) {
for (int c=1; c<C+1; ++c) {
sum = sum + c;
}
}
return Py_BuildValue("l", sum);
}
static PyMethodDef PalMethods[] = {
{"f1", pal_f1, METH_VARARGS, "To calculate the sum of numbers"},
{NULL, NULL}
};
static struct PyModuleDef palmodule = {
PyModuleDef_HEAD_INIT,
"pal", /* name of module */
"Module with Function f1", /* module documentation*/
-1, /* size of per-interpreter state or -1 if module keeps state in global variables.*/
PalMethods
};
PyMODINIT_FUNC PyInit_pal(void) {
return PyModule_Create(&palmodule);
}
Step 2. Create a file called "setup.py"
from distutils.core import setup, Extension
setup (name='pal', version='1.0', ext_modules=[Extension('pal', ['palmodule.c'])])
Step 3. Install the extension using the following command:
sudo python3 setup.py install
Step 4. Now open the python3 interpreter and do the following:
>>> from pal import f1
>>> f1(5)
35
Tuesday, May 15, 2018
Tuesday, April 10, 2018
Apache2 configuration to run both django and flask in one server.
# Under /etc/apache2/sites-available/ add a file say multi_sites.conf with the following contents
project name of django is DP and project name of flask is FP:
<VirtualHost *>
Alias /static /../DP/static
<Directory /.../DP/static>
Require all granted
</Directory>
<Directory /../DP/DP>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess python-path=/../DP/
WSGIProcessGroup DP
WSGIScriptAlias / /../DP/DP/wsgi.py
</VirtualHost>
<VirtualHost *>
Alias /static /../FP/static
<Directory /../FP/static>
Require all granted
</Directory>
<Directory /../FP/>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess ocean python-path=/../FP/
WSGIScriptAlias / /../FP/wsgi.py
</VirtualHost>
3. Enable sites:
sudo a2ensite multi_sites.conf
sudo a2dissite 000-default.conf
sudo apache2ctl restart
Saturday, December 5, 2015
Performance Comparison of C, Swift, Go and Python
To compare the performance of different languages, let us write a simple algorithm that does the following. Say the given number is 5. Then the algorithm calculates the sum of all numbers for numbers from 1 to 5.
1+ (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35
C Program - test.c:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
long sum = 0;
int V = atoi(argv[1]);
for (int C=1; C<=V; ++C) {
for (int c=1; c<C+1; ++c) {
sum = sum + c;
}
}
printf("sum = %li\n",sum);
return 0;
}
Swift Program - test.swift:
var sum = 0;
var V = Int(Process.arguments[1])
for var C = 1; C <= V; ++C {
for var c = 1; c < C+1; ++c {
sum = sum + c;
}
}
print("sum = \(sum)");
Go Program - test.go:
package main
import "os"
import "fmt"
import "strconv"
func main() {
sum := 0
V,err := strconv.Atoi(os.Args[1])
for I:=1; I<=V; I++ {
for i:=1; i<I+1; i++ {
sum = sum + i
}
}
if err == nil {
fmt.Println("sum =",sum)}
}
Python C extension: Say we want to create a module named "pal" with a function called "f1" to just do the same as test.c
Step 1. Create a file called "palmodule.c" :
#include <Python.h>
static PyObject * pal_f1(PyObject *self, PyObject *args)
{
int x;
PyArg_ParseTuple(args, "i", &x);
long sum = 0;
for (int C=1; C<=x; ++C)
{
for (int c=1; c<C+1; ++c)
{
sum = sum + c;
}
}
return Py_BuildValue("l", sum);
}
static PyMethodDef PalMethods[] = {
{"f1", pal_f1, METH_VARARGS},
{NULL, NULL}
};
static struct PyModuleDef palmodule = {
PyModuleDef_HEAD_INIT,
"pal", /* name of module */
"", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
PalMethods
};
PyMODINIT_FUNC PyInit_pal(void)
{
return PyModule_Create(&palmodule);
}
Step 2. Create a file called "setup.py"
from distutils.core import setup, Extension
setup(name='pal', version='1.0', ext_modules=[Extension('pal', ['palmodule.c'])])
Step 3. Install the extension using the following command:
sudo python3 setup.py install
Step 4. Now write a python program "testc.py" using the pal module:
#!/usr/bin/python3
from sys import argv
from pal import f1
print("sum = %s" %f1(int(argv[1])))
Runtime Performance Comparison
Run the above four different programs one by one and find the time taken as shown below. The number used is 100,000 :
1. C program
$ time ./test.o 100000
sum = 166671666700000
real 0m10.999s
user 0m10.992s
sys 0m0.000s
sum = 166671666700000
real 0m19.318s
user 0m19.304s
sys 0m0.000s
3. Go program
$ time ./test.g 100000
sum = 166671666700000
real 0m2.155s
user 0m2.152s
sys 0m0.004s
3. Python C extension program
$ time ./testc.py 100000
sum = 166671666700000
real 0m1.618s
user 0m1.616s
sys 0m0.000s
This shows that Python with C extension is the best that takes the least time. The second best is "Go", then "C". Swift is the worst among them.
1+ (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35
C Program - test.c:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
long sum = 0;
int V = atoi(argv[1]);
for (int C=1; C<=V; ++C) {
for (int c=1; c<C+1; ++c) {
sum = sum + c;
}
}
printf("sum = %li\n",sum);
return 0;
}
Swift Program - test.swift:
var sum = 0;
var V = Int(Process.arguments[1])
for var C = 1; C <= V; ++C {
for var c = 1; c < C+1; ++c {
sum = sum + c;
}
}
print("sum = \(sum)");
Go Program - test.go:
package main
import "os"
import "fmt"
import "strconv"
func main() {
sum := 0
V,err := strconv.Atoi(os.Args[1])
for I:=1; I<=V; I++ {
for i:=1; i<I+1; i++ {
sum = sum + i
}
}
if err == nil {
fmt.Println("sum =",sum)}
}
Python C extension: Say we want to create a module named "pal" with a function called "f1" to just do the same as test.c
Step 1. Create a file called "palmodule.c" :
#include <Python.h>
static PyObject * pal_f1(PyObject *self, PyObject *args)
{
int x;
PyArg_ParseTuple(args, "i", &x);
long sum = 0;
for (int C=1; C<=x; ++C)
{
for (int c=1; c<C+1; ++c)
{
sum = sum + c;
}
}
return Py_BuildValue("l", sum);
}
static PyMethodDef PalMethods[] = {
{"f1", pal_f1, METH_VARARGS},
{NULL, NULL}
};
static struct PyModuleDef palmodule = {
PyModuleDef_HEAD_INIT,
"pal", /* name of module */
"", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
PalMethods
};
PyMODINIT_FUNC PyInit_pal(void)
{
return PyModule_Create(&palmodule);
}
from distutils.core import setup, Extension
setup(name='pal', version='1.0', ext_modules=[Extension('pal', ['palmodule.c'])])
Step 3. Install the extension using the following command:
sudo python3 setup.py install
Step 4. Now write a python program "testc.py" using the pal module:
#!/usr/bin/python3
from sys import argv
from pal import f1
print("sum = %s" %f1(int(argv[1])))
Runtime Performance Comparison
Run the above four different programs one by one and find the time taken as shown below. The number used is 100,000 :
1. C program
$ time ./test.o 100000
sum = 166671666700000
real 0m10.999s
user 0m10.992s
sys 0m0.000s
2. Swift program
$ time ./test.sw 100000sum = 166671666700000
real 0m19.318s
user 0m19.304s
sys 0m0.000s
3. Go program
$ time ./test.g 100000
sum = 166671666700000
real 0m2.155s
user 0m2.152s
sys 0m0.004s
$ time ./testc.py 100000
sum = 166671666700000
real 0m1.618s
user 0m1.616s
sys 0m0.000s
This shows that Python with C extension is the best that takes the least time. The second best is "Go", then "C". Swift is the worst among them.
Wednesday, September 30, 2015
Yield Expression and Generator Function in Python
Yield expressions are only used within a generator function. Here is an example:
>>def pp():
x = yield #1
yield x*x #2
yield x*x*x #3
yield x*x*x*x #4
yield x*x*x*x*x #5
yield x*x*x*x*x*x #6
>>g = pp()
>>next(g) #starts the generator and executes line #1
>>g.send(5) #sends value 5 to x at line #2 and gets the result
25
>>def pp():
x = yield #1
yield x*x #2
yield x*x*x #3
yield x*x*x*x #4
yield x*x*x*x*x #5
yield x*x*x*x*x*x #6
>>g = pp()
>>next(g) #starts the generator and executes line #1
>>g.send(5) #sends value 5 to x at line #2 and gets the result
25
>>next(g) #gets the result of next line #3
125
>>next(g) #gets the result of next line #4
625
>>g.send(2) #gets the result of next line #5
3125 #cannot send a new value in the middle of execution
>>next(g) #gets the result of next line #6
15625
>>next(g) #Throws StopIteration exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Saturday, September 12, 2015
Vim AutoCompletion for Python
Installing Pydiction to enable Auto-Completion for Python in Vi (Vim) editor:
1. First install Pathogen using the System Package Manager.
2. Download vimogen int the home directory using command-line:
git clone https://github.com/rkulla/vimogen.git
3. Create .vim and .bundle directories by command-line:
mkdir ~/.vim
mkdir ~/.vim/bundle
4. Create file .vimogen_repos with the following content:
echo "https://github.com/rkulla/pydiction.git" > ~/.vimogen_repos
5. Run vimogen by command-line:
~/vimogen/vimogen.sh (and type 1 to install)
This will install pydiction in directory ~/.vim/bundle/
5. Under ~.vim do the following link:
cd ~/.vim
ln -s bundle/pydiction/after .
6. edit ~/.vimrc file and add the following lines:
filetype plugin on
let g:pydiction_location = '~/.vim/bundle/pydiction/complete-dict'
if has("autocmd")
autocmd FileType python set complete+=k/path/to/pydiction iskeyword+=.,(
endif " has("autocmd")
That all you need to do.
Now open an existing or new *.py file and check auto-completion by typing any python keyword or module partially and press tab to show the available choices.
For further reading check the following links.
http://www.vim.org/scripts/script.php?script_id=850
http://rkulla.github.io/pydiction/
1. First install Pathogen using the System Package Manager.
2. Download vimogen int the home directory using command-line:
git clone https://github.com/rkulla/vimogen.git
3. Create .vim and .bundle directories by command-line:
mkdir ~/.vim
mkdir ~/.vim/bundle
4. Create file .vimogen_repos with the following content:
echo "https://github.com/rkulla/pydiction.git" > ~/.vimogen_repos
5. Run vimogen by command-line:
~/vimogen/vimogen.sh (and type 1 to install)
This will install pydiction in directory ~/.vim/bundle/
5. Under ~.vim do the following link:
cd ~/.vim
ln -s bundle/pydiction/after .
6. edit ~/.vimrc file and add the following lines:
filetype plugin on
let g:pydiction_location = '~/.vim/bundle/pydiction/complete-dict'
if has("autocmd")
autocmd FileType python set complete+=k/path/to/pydiction iskeyword+=.,(
endif " has("autocmd")
That all you need to do.
Now open an existing or new *.py file and check auto-completion by typing any python keyword or module partially and press tab to show the available choices.
For further reading check the following links.
http://www.vim.org/scripts/script.php?script_id=850
http://rkulla.github.io/pydiction/
Thursday, June 4, 2015
Python Interpreter - Removing leading dots.
Create a .pythonrc.py file with following lines in the default home directory (~):
import sys
sys.ps1 = '>>'
sys.ps2 = ''
Add the following line in .bashrc or profile file to export variable.
export PYTHONSTARTUP="~/.pythonrc.py"
Wednesday, June 3, 2015
Use string variable or string to call a function
In python locals() return a dictionary representing the current local symbol table with all functions as dictionaries.
Say you have a function called "Func()". The locals() will return a dictionary with "Func" as shown below:
{....., 'Func': <function Func at 0x7f9ff50a5268>, ...........}
Now you can the call the function 'Func()' by the calling the dictionary key as below:
Direct String Substitution:
locals() ['Func'] ()
Variable Substitution:
F = "Func"
locals() ['F']
You can also use globals() instead of locals() if you need global system table.
If the function is part of a class then use getattr(class,"function")()
Say you have a function called "Func()". The locals() will return a dictionary with "Func" as shown below:
{....., 'Func': <function Func at 0x7f9ff50a5268>, ...........}
Now you can the call the function 'Func()' by the calling the dictionary key as below:
Direct String Substitution:
locals() ['Func'] ()
Variable Substitution:
F = "Func"
locals() ['F']
You can also use globals() instead of locals() if you need global system table.
If the function is part of a class then use getattr(class,"function")()
Tuesday, May 26, 2015
Decorators in Python
In Python Decorators are functions of functions. It is a wrapper function that wraps a regular function to modify its results.
For example, say you have a function to capitalize the first letter of names. Now you want to add another function on top of this to include the title (Mr/Ms) depending upon the gender. This can be achieved by defining a decorator function to add the title.
Decorator Function to add the title (Mr/Ms) based on gender:
def Title(func):
def new(*args, **kwds):
if kwds['gender'] == 'male': return ("Mr "+func(*args, **kwds))
elif kwds['gender'] == 'female': return ("Ms "+func(*args, **kwds))
else: return func(*args, **kwds)
return new
For example, say you have a function to capitalize the first letter of names. Now you want to add another function on top of this to include the title (Mr/Ms) depending upon the gender. This can be achieved by defining a decorator function to add the title.
Decorator Function to add the title (Mr/Ms) based on gender:
def Title(func):
def new(*args, **kwds):
if kwds['gender'] == 'male': return ("Mr "+func(*args, **kwds))
elif kwds['gender'] == 'female': return ("Ms "+func(*args, **kwds))
else: return func(*args, **kwds)
return new
Regular function to capitalize the first letter with decorator:
@Title
def Capitalize(name,gender=''):
return name.title()
Now call the regular function as below:
Capitalize('john travolta',gender='male')
result >>> 'Mr John Travolta'
Capitalize('catherine zeta jones',gender='female')
result >>> 'Ms Catherine Zeta Jones'
Wednesday, August 6, 2014
To compile Python Scripts
Python scripts with .py extension can be compiled to binary files with .pyc extension by the following command:
python -m compileall ./
This command compiles all scripts in the current directory.
Tuesday, July 22, 2014
Python Auto Completion in Terminal
Auto completion is a nice feature for Terminal commands but inside a Python interpreter it does not work. To enable auto-completion within python interpreter, we need to do the following.
Step 1: Create a file pythonrc at /etc/ directory and add the following lines in the file:
from readline import parse_and_bind
import rlcompleter
parse_and_bind("tab: complete")
Step2: In the file at /etc/bash.bashrc , add the following line
export PYTHONSTARTUP=/etc/pythonrc
Step3: Restart the terminal and invoke python interpreter.
Step 1: Create a file pythonrc at /etc/ directory and add the following lines in the file:
from readline import parse_and_bind
import rlcompleter
parse_and_bind("tab: complete")
export PYTHONSTARTUP=/etc/pythonrc
Step3: Restart the terminal and invoke python interpreter.
Friday, November 22, 2013
Control Flow Loops in Python
For Loop to reassign items in a list:
>>> s = [1,2,3]
>>> for n in range(len(s)):
s[n] = s[n]*2
>>> s
[2, 4, 6]
>>> s = [1,2,3]
>>> for n in range(len(s)):
s[n] = s[n]*2
>>> s
[2, 4, 6]
Call Python Within Shell Script
Shell scripts are easier to write but they lack the features provided by a programming language like python. But instead python can be used within shell scripts. Here are two examples.
1. To get the file name ‘File’ from the full path ‘Path’:
File=`python -c "print '$Path'.split('/')[-1]"`
2. To get the directory ‘Dir’ from the full path ‘Path’ of file ‘File’:
Dir=`python -c "print '$Path'.rstrip(str('$File'))"`
1. To get the file name ‘File’ from the full path ‘Path’:
File=`python -c "print '$Path'.split('/')[-1]"`
2. To get the directory ‘Dir’ from the full path ‘Path’ of file ‘File’:
Dir=`python -c "print '$Path'.rstrip(str('$File'))"`
Python Unicode
#In Python 2.X
#To convert Unicode to character:
>>> for x in range(0x6000,0x6020,1):
print unichr(x),
怀 态 怂 怃 怄 怅 怆 怇 怈 怉 怊 怋 怌 怍 怎 怏 怐 怑 怒 怓 怔 怕 怖 怗 怘 怙 怚 怛 怜 思 怞 怟
#In Python 3.X:
#To convert Unicode to character:
#To convert Unicode to character:
>>> for x in range(0x6000,0x6020,1):
print unichr(x),
怀 态 怂 怃 怄 怅 怆 怇 怈 怉 怊 怋 怌 怍 怎 怏 怐 怑 怒 怓 怔 怕 怖 怗 怘 怙 怚 怛 怜 思 怞 怟
#In Python 3.X:
#To convert Unicode to character:
>>> for x in range(0x6000,0x6020,1):
print(chr(x),end=' ')
怀 态 怂 怃 怄 怅 怆 怇 怈 怉 怊 怋 怌 怍 怎 怏 怐 怑 怒 怓 怔 怕 怖 怗 怘 怙 怚 怛 怜 思 怞 怟#To convert character to Unicode:
>>> hex(ord('怀'))
’0×6000′
>>> for n in ‘सत्यमेव जयते’:
print(ord(n), end=',')
2360,2340,2381,2351,2350,2375,2357,32,2332,2351,2340,2375,
Python Regular Expressions
Python has a ‘re’ module to handle regular expressions. Here are some examples.
>>> import re
#Example 1: To extract the contents within double quotes in a string
>>> s = 'customer name is "FirstName LastName"'
>>> re.findall('".*"',s)
['"FirstName LastName"'] #The result is a list
#Example 2: To extract the individual words from a combined word like ‘FirstName’
>>> s = 'FirstName'
>>> re.findall('[A-Z][a-z]+',s)
['First', 'Name'] #The result is a list.
>>> ''.join(re.findall('[A-Z][a-z]+',s))
'FirstName' #To get the string from the list
#Example 3: To replace all numbers with a ‘.’ suffix’
>>> s = '1 one 11 eleven'
>>> re.sub("(\d)( )","\\1.\\2",s)
'1. one 11. eleven'
>>> import re
#Example 1: To extract the contents within double quotes in a string
>>> s = 'customer name is "FirstName LastName"'
>>> re.findall('".*"',s)
['"FirstName LastName"'] #The result is a list
#Example 2: To extract the individual words from a combined word like ‘FirstName’
>>> s = 'FirstName'
>>> re.findall('[A-Z][a-z]+',s)
['First', 'Name'] #The result is a list.
>>> ''.join(re.findall('[A-Z][a-z]+',s))
'FirstName' #To get the string from the list
#Example 3: To replace all numbers with a ‘.’ suffix’
>>> s = '1 one 11 eleven'
>>> re.sub("(\d)( )","\\1.\\2",s)
'1. one 11. eleven'
Subscribe to:
Posts (Atom)