Tuesday, December 15, 2015

Python Data Structures Collections Deque

Deque
A double-ended queue, or deque, supports adding and removing elements from either
end. The more commonly used structures, stacks, and queues

Example:
1
2
3
4
5
6
7
8
9
def deque_example():
    import collections
    d = collections.deque('abcdefg')
    print 'Deque:', d
    print 'Length:', len(d)
    print 'Left end:', d[0]
    print 'Right end:', d[-1]
    d.remove('c')
    print 'remove(c):', d
Output:
1
2
3
4
5
6
7
output:
$ python collections_deque.py
Deque: deque('a', 'b', 'c', 'd', 'e', 'f', 'g'])
Length: 7
Left end: a
Right end: g
remove(c): deque([a, b, d, e, f, g])

Populating
A deque can be populated from either end, termed “left” and “right” in the Python
implementation.

Example:

1
2
3
4
5
6
7
output:
$ python collections_deque.py
Deque: deque([a, b, c, d, e, f, g])
Length: 7
Left end: a
Right end: g
remove(c): deque([a, b, d, e, f, g])
Output:
1
2
3
4
5
$ python collections_deque_populating.py
extend : deque([a, b, c, d, e, f, g])
append : deque([a, b, c, d, e, f, g, h])
extendleft: deque([5, 4, 3, 2, 1, 0])
appendleft: deque([6, 5, 4, 3, 2, 1, 0])

Consuming
Similarly, the elements of the deque can be consumed from both ends or either end,
depending on the algorithm being applied

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def deque_consume():
    import collections
    print 'From the right:'
    d = collections.deque('abcdefg')
    while True:
        try:
            print d.pop()
        except IndexError:
            break
    print
    print '\nFrom the left:'
    d = collections.deque(xrange(6))
    while True:
        try:
            print d.popleft()
        except IndexError:
            break
    print

deque_comsume()

Output:
1
2
3
4
5
$ python collections_deque_consuming.py
From the right:
g f e d c b a
From the left:
0 1 2 3 4 5

Rotating
Another useful capability of the deque is to rotate it in either direction, to skip over
some items.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def deque_rotate():
    import collections
    d = collections.deque(xrange(10))
    print 'Normal :', d
    d = collections.deque(xrange(10))
    d.rotate(2)
    print 'Right rotation:', d
    d = collections.deque(xrange(10))
    d.rotate(-2)
    print 'Left rotation :', d

deque_rotate()

Monday, December 14, 2015

Python Data Structures Collections

DATA STRUCTURES:
                   Python includes several standard programming data structures, such as list, tuple,

dict, and set, as part of its built-in types
                   The collections module includes implementations of several data structures
that extend those found in other modules. For example, Deque is a double-ended queue
that allows the addition or removal of items from either end. The defaultdict is a
dictionary that responds with a default value if a key is missing, while OrderedDict
remembers the sequence in which items are added to it. And namedtuple extends the
normal tuple to give each member item an attribute name in addition to a numeric
index.

collections—Container Data Types:
The collections module includes container data types beyond the built-in types
list, dict, and tuple.

Counter
A Counter is a container that tracks how many times equivalent values are added.

Initializing
Counter supports three forms of initialization. Its constructor can be called with a
sequence of items, a dictionary containing keys and counts, or using keyword arguments
mapping string names to counts.

Examples:
1.
1
2
3
4
5
6
7
import collections
c = collections.Counter()
print "Initial :",c
c.update('abcdaab')
print "Sequence:",c
c.update({'a':10,'d':5})
print "Dict :",c

1
2
3
4
5
>>> 
Initial : Counter()
Sequence: Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
Dict : Counter({'a': 13, 'd': 6, 'b': 2, 'c': 1})
>>> 

2. Count the number for word in the file 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def read_count_word():
    fd=open("input_test.txt",'r')
    word_cout=0
    digit_count=0
    import collections
    c=collections.Counter()
    for each_line in fd.readlines():
        each_word=each_line.split()
        c.update(each_word)
    print "How many Words and count :"
    print c

3. Common letters in the directory


1
2
3
4
5
6
7
8
 import collections
    c = collections.Counter()
    with open('C:\Users\ifocus\Downloads\Shashi_python', 'rt') as f:
        for line in f:
            c.update(line.rstrip().lower())
    print 'Most common:'
    for letter, count in c.most_common(3):
        print '%s: %7d' % (letter, count)


4. Set Operations on the counter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def couter_set_opertaion():
    import collections
    c1 = collections.Counter(['a','a','b','c','a','d'])
    c2 = collections.Counter('alphabet')
    print 'C1:', c1
    print 'C2:', c2
    print "\nCombined counts:"
    print c1 + c2
    print "\nSubtraction:"
    print c1 - c2
    print '\nIntersection (taking positive minimums):'
    print c1 & c2
    print '\nUnion (taking maximums):'
    print c1 | c2

Monday, November 30, 2015

Python Control Statements

Break Statement:



break
Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#!/usr/bin/python

for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print 'Current Letter :', letter
  
var = 10                    # Second Example
while var > 0:              
   print 'Current variable value :', var
   var = var -1
   if var == 5:
      break

print "Good bye!"
Continue:
continue
Example:
1
2
3
4
5
6
7
str1="hello"
for i in str1: # 'hello'
    if i=='l':
  continue
  print "Hai"
    else:
        print i
Pass:
Syntax:
pass
Example:
1
2
3
4
5
6
7
str1="hello"
for i in str1:
    if i == 'e':
        pass
        print "Whats up"
    else:
        print i

Python Conditional Statements

1. Basic IF Statement :
if condition:
    Block 
    statements 

Example:
1
2
3
4
5
6
if True:
    print "its True Block"
if 10:
    print "its True Block"
if 1<2:
    print "Yes its True 1 is lesser then 2"
2. IF.. Else... Statement
if condition:
    True Block
else:
    False Block
Example:
a=1
b=2
if a<b:
    print "its b is big"
else:
    print "its a is big"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
if True:
    print "its True Block"
 
if not 23:
    print "Yes i am not 23"
else:
    print "Yes i am 23"

if None:
    print "Not none"
else:
    print "I am NOne"

3. IF.. Elif...elif... Statement

if condition1:
    Cond1 Block 
elif Condition2:
    Cond2 Block
elif Condition3:
    Cond3 Block 
 .
 .
4. IF.. Elif...elif...else... Statement

if condition1:
    Cond1 Block 
elif Condition2:
    Cond2 Block
elif Condition3:
    Cond3 Block 
 .
 .
else:
    Else Block
Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
a=int(raw_input("Enter a value"))
b=int(raw_input("Enter b value"))
c=int(raw_input("Enter c value"))

if a<b and b<c:
    print "C is big"
elif a>b and a>c:
    print "A is big"
else:
    print "B is big"
5. Nested IF.. Elese Statement
if Condition1:
    if Condition2:
     Condition2 True Block 
 else:
     Condition2 False Block 
else:
    if Condition3:
     Condition3 True Block 
 else:
     Condition3 False Block
Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
if a<b:
   if b<c:
       print "C is big"
   else:
       print "B is big"
else:
   if a>c:
       print "A is Big"
   else:
       print "C is big"

Python Looping Statements

Python For Loop:

           If a sequence contains an expression list, it is evaluated first. Then, the first item 
in the sequence is assigned to the iterating variable iterating_var. Next, the statements 
block is executed. Each item in the list is assigned to iterating_var, and the statement(s) 
block is executed until the entire sequence is exhausted.



for iterating_var in sequence:
   statements(s)
Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
n=input("Enter the value:")
for i in range(n):
    print "i:",i

str1=raw_input("Enter the String:")
for i in str1:
    print "i:",i
    
n=input("Enter the value:")
l=[]
for i in range(n):
 en=raw_input("Enter the String:")
 l.append(en)
Prime Numbers:
1
2
3
4
5
6
for num in range(10,20): #[10,11,12,12,....19]
    for i in range(2,num):
        if num%i == 0:
            break
    else:#else for
        print "prim Num",num
Fibonac Series :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def fib_gen(n):
#fib 0,1,1,2,3,5...
    l=[0,1]
    for i in range(2,n):
        fib=l[i-1]+l[i-2]
        l.append(fib)
    return l

n=input("Enter Number")
l=fib_gen(n)
print "Fib List:",l

While Statements :
            Statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.
while expression:
   statement(s)
Example:
1
2
3
4
a=1
while a<10:
   print a
   a=a+1
Prime Number using while:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
a=10
n=200
b=1
while a< n:
 c=2
 while c<a-1:
  if a%c==0:
   break
  c=c+1 
 else:
     print "Prime:",a
     
 if b==10:
  print ">>",b
  break
 else:
     b+=1
 a=a+1#a+=1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
c=1
l=[]
p="="*30
n=raw_input("Enter number how many std ")
while c<int(n):
    name=raw_input("Enter Name")
    age=raw_input("Enter Age")
    l.append({'Name':name,"Age":age})
    c=c+1
    
print p
print "        Std Details      "
print p
for i in l:
    print i['Name']
    print i['Age']

Thursday, April 10, 2014

Python Syllabus



Python Syllabus
Core Python

Introduction
  • History
  • Features
  • Setting up path
  • Working with Python
  • Basic Syntax
  • Variable and Data Types
  • Operator
Conditional Statements
  • If
  • If- else
  • Nested if-else

Looping
  • For
  • While
  • Nested loops
Control Statements
  • Break
  • Continue
  • Pass

String Manipulation
  • Accessing Strings
  • Basic Operations
  • String slices
  • Function and Methods

Lists
  • Introduction
  • Accessing list
  • Operations
  • Working with lists
  • Function and Methods
Tuple
  • Introduction
  • Accessing tuples
  • Operations
  • Working
  • Functions and Methods

Dictionaries
  • Introduction
  • Accessing values in dictionaries
  • Working with dictionaries
  • Properties
  • Functions

Functions
  • Defining a function
  • Calling a function
  • Types of functions
  • Function Arguments
  • Anonymous functions
  • Global and local variables

Modules
  • Importing module
  • Math module
  • Random module
  • Packages
  • Composition

Input-Output
  • Printing on screen
  • Reading data from keyboard
  • Opening and closing file
  • Reading and writing files
  • Functions

Exception Handling
  • Exception
  • Exception Handling
  • Except clause
  • Try ??? finally clause
  • User Defined Exceptions
Regular expressions
  • Match function
  • Search function
  • Matching VS Searching
  • Modifiers
  • Patterns

Tuesday, February 14, 2012

How to write a simple CGI script using Python :
step 1: Install apache server in your linux machine:
           for installation : sudo apt-get install --purge apache2 apache2-utils
           if remove :          sudo apt-get remove --purge apache2 apache2-utils
             Now do your typical installation:
             "sudo apt-get install apache2"
step 2:
            First, you need an Apache server on your Linux/Mac OS/Windows box. If you are gonna use data base, you need a database server. There are tons of blogs addressing these issues. So I won't be gossipy here. Suppose everything we mention below happens on your server-even web browsing.

             Second, configure cgi in Apache. There are many ways to run a Python program on a web/http interface. I think CGI is the easiest. Assume you are on your own server and using all default settings. On Ubuntu Linux 9.04, the default configuration file for your default website is /etc/apache2/sites-available/default Open it, find the part for cgi directory, and make it like this

 _________________________________________________________________________________
 ScriptAlias /cgi-bin/ /var/www/cgi-bin/
        <Directory "/var/www/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
                AddHandler cgi-script .py 
              # tell Apache to handle every file with .py suffix as a cgi program
                AddHandler default-handler .html .htm 
              # tell Apache to handle HTML files in regular way
        </Directory>
______________________________________________________________________________________________
 
 
 
The line
ScriptAlias /cgi-bin/ /var/www/cgi-bin/ specifies the path of cgi codes and the actual directory of your program. So when you type http://127.0.0.1/cgi-bin, the Apache will look into the directory /var/www/cgi-bin/ of your localhost.
Now restart your apache. On Ubuntu Linux, by default installation and configuration, it is

sudo /etc/init.d/apache2 restart
Third, write up a Hello, World! program. Save it as hello.py and give it execution privilege for anyone.

1
2
3
4
5
6
#!/usr/bin/env python
print "Content-Type: text/html"
print print """\ <html>
<head><title>First Python HTTP Programming </title></head>
<body> <h2>Hello World!</h2>
 </body> </html> """
Now open http://127.0.0.1/cgi-bin/hello.py in your web browser and you shall see a hello world in it.

If you have any error, e.g., 500 error, please check your Apache log file. It shall tell you something. You can find errors like what you have seen from a standard Python interpreter.