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

No comments:

Post a Comment