Tuesday, 17 January 2012

Taste of Python Power

Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs. Python runs on Windows, Linux/Unix, Mac OS X, and has been ported to the Java and .NET virtual machines. Python is free to use, even for commercial products, because of its OSI-approved open source license. The below is a quick taste of the power of Python language:


List Comprehensions
print [x+1 for x in xrange(10) if x%3 == 0]

[1, 4, 7, 10]
Dictionary Defaults
my_dict = {}
world = my_dict.get('hello', 'world')
print world

world
Filter
from math import sqrt

def prime(n):
    if n < 1 : return False
    for d in range(2, int(sqrt(n))+1):
        if n % d == 0: return False
    return True

print [n for n in range(20) if prime(n)]

print filter(prime, range(20))

[1,2,3,5,7,11,13,17,19]
[1,2,3,5,7,11,13,17,19]
Unzip
tups = [(1,4,7),(2,5,8),(3,6,9)]
t0s, t1s, t2s = zip(*tups)
print t0s
print t1s
print t2s

(1,2,3)
(4,5,6)
(7,8,9)
dict() and zip() make for a powerful combination
voters = ['friends','neighbors','countrymen']
counts = [10,5,800]
print dict(zip(voters,counts))

votes = ['yes',66,'no',77,'abstain',9]
print dict(zip(votes[:-1:2],votes[1::2]))

{‘neighbours’:5, ‘countrymen’:800, ‘friends’:10}

{‘yes’:66, ’abstain’:9, ’no’:77}
Triple quotes
print """Dear John,
How are you?
Best of luck, George."""

Dear John,
How are you?
Best of luck, George.
Map
print map(int, "10 20 30".split())

[10,20,30]
Multiple Return Values
def get_center():
    return (10, 10)

x, y = get_center()
print "The center is at X: %d, Y: %d" % (x, y)

The center is at X: 10, Y: 10
Expanding Arrays to Function Arguments
def add(n1, n2):
    return n1 + n2

numbers = [3, 4]
print add(*numbers)

7
Collections
import collections
d=collections.defaultdict(int)
d["never seen before"] += 1
print d["never seen before"]

1
Generator Functions
def lottery_numbers():
    my_numbers = [1,3,2,5,4,6]

    for n in my_numbers:
        if n > 3:
            yield n+10
        else:
            yield n

for n in lottery_numbers():
    print n

1
3
2
15
14
16
Zip
names = ['john', 'peter', 'robert']
ages = [24, 26, 35]
cars = ['BMW', 'Audi', 'Ford']

print zip(names, ages, cars)

[('john', 24, 'BMW'), ('peter', 26, 'Audi'), ('robert', 35, 'Ford')]
Ordered and Named Function Arguments
def f(*args, **kwargs):
    print(args)
    print(kwargs)

f(1,2,3,named1="keyword arg1", another="another kwarg")

(1, 2, 3)
{'named1': 'keyword arg1', 'another': 'another kwarg'}
Locals and Strings
world = "earth"
print "hello %(world)s" % locals()

hello earth
Glass Half Empty?
from __future__ import division
import sys

print 1/2 + 1/2
print sys.version

1.0
2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)]
Set Comprehensions
print {1, 2, 2, 3, 1}

names = ["Foo", "bar", "foo", "Baz", "CATS", "dogs"]
print {name.upper() for name in names if name[0] in 'fFbB'}

set([1, 2, 3])
set(['BAZ', 'FOO', 'BAR'])
Functions as Objects
def talk(text):
    print text

def think(idea):
    print "thinking about %s" % idea

def do_something(what, with_what):
    what(with_what)

do_something(talk, 'hello!')
do_something(think, 'food...')

hello!
thinking about food...
Funception
def outside(a, b):
    def inside(x):
        return x + 5
    return inside(a) * inside(b)

print outside(1, 2)

42
Addition made easy
print eval('+'.join(map(str, [1, 1])))

2

7 comments:

  1. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks from every one of us.

    Best AWS Training in Chennai | Amazon Web Services Training in Chennai

    ReplyDelete
  2. Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.

    angularjs Training in chennai
    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    ReplyDelete
  3. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.
    python training in pune | python training institute in chennai | python training in Bangalore

    ReplyDelete
  4. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    Devops Training courses
    Devops Training in Bangalore
    Best Devops Training in pune
    Devops interview questions and answers

    ReplyDelete
  5. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    Java training in Annanagar | Java training in Chennai

    Java training in Chennai | Java training in Electronic city

    ReplyDelete
  6. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa interview questions and answers
    automation anywhere interview questions and answers
    blueprism interview questions and answers
    uipath interview questions and answers
    rpa training in chennai

    ReplyDelete