Saturday, July 26, 2014

Python 2 by example

Python 2.7 syntax examples:
Code samples at : https://github.com/rwatsh/python 

1.       Math:
2**3 = 8 , where, ** is exponent operator
+, -, *, / = math operators
% = modulo operator
2.       Comments:
# - single line comment

“”” my multi line
comment “””
3.       Print:
print(“%.2f”, total) -> will print total rounded to 2 decimal places.
4.       Escape char:
'There\'s a snake in my boot!'
Not required when using double quotes for string.
5.       String:
fifth_letter = "MONTY"[4]
print fifth_letter => prints Y
parrot = "Norwegian Blue"
print len(parrot)
print parrot.lower()
print parrot.upper()
pi = 3.14
print str(pi) => str() converts non-strings to string
Methods that use dot notation only work with strings.
On the other hand, len() andstr() can work on other data types.
print "Spam " + "and " + "eggs"
print "The value of pi is around " + str(3.14)
string_1 = "Camelot"
string_2 = "place"

print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
ð  Let's not go to Camelot. 'Tis a silly place.
String slicing:
s = "Charlie"

print s[0]
# will print "C"

print s[1:4]
# will print "har"
Getting i/p and printing o/p:
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")

print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)
6.       Datetime library:
from datetime import datetime
print datetime.now() => 2014-07-25 17:42:13.304805
print now.month => 7
print now.day => 25
print now.year => 2014
print '%s/%s/%s' % (now.month, now.day, now.year) => 7/25/2014
print '%s:%s:%s' % (now.hour, now.minute, now.second) =>17:48:28

7.       Comparison:
==, !=, <, >, <=, >=
8.       Logical: and, or, not
9.       Conditional: if, elif, else
def clinic():
    print ("You\'ve just entered the clinic!")
    print ("Do you take the door on the left or the right?")
    answer = input("Type left or right and hit 'Enter'.").lower()
    if answer == "left" or answer == "l":
        print ("This is the Verbal Abuse Room, you heap of parrot droppings!")
    elif answer == "right" or answer == "r":
        print ("Of course this is the Argument Room, I've told you that already!")
    else:
        print ("You didn't pick left or right! Try again.")
        clinic()

clinic()
10.   Functions:
See above example –
def [function_name(param1, param2)]:
                x = 2
                return x
11.   Import:
a.       Generic import: Import a module by name. Ex:
import math

print math.sqrt(25)
b.      Function import:
from [module] import [function]

from math import sqrt
print sqrt(25)
c.       Universal import:
from [module] import *

from math import *
print sqrt(25)
d.      Check everything a module has:
Import math
Print dir(math)
12.   Built-in functions: max, min, abs, type
Max(1,2,3) => 3
Min(1,2,3) => 1
Abs(-10) => 10
Print type(1) => or type(num) == int
13.   List:
zoo_animals = ["pangolin", "cassowary", "cat", "dog"]
print "The first animal at the zoo is the " + zoo_animals[0]
print len(zooanimals)
print zooanimals[0:2] => 1st and 2nd elements in the list
pets = zooanimals[2:4] or zooanimals[2:] => cat and dog => slicing the list.
Cat_index = zooanimals.index(“cat”)
Zoonimals.insert(cat_index, “cobra”) => ["pangolin", "cassowary", “cobra”, "cat", "dog"]
Zooanimals.sort() => sort the list.
zooanimals.remove(“cat”) => remove element from list
                pets[] => empty list
                print “----“.join(zooanimals) => pangolin ---- cassowary ---- cobra ---- cat ----- dog
               
                List Comprehension syntax:      

                my_list = range(51)
evens_to_50 = [i for i in range(51) if i % 2 == 0]

List Slicing:
List slicing allows us to access elements of a list in a concise manner. The syntax looks like this:

[start:end:stride]

                my_list = range(1, 11) # List of numbers 1 - 10

# print all odds from start to finish so no need to specify the start and end only need stride.
print my_list[::2]
# reverse a list
backwards = my_list[::-1]


to_21 = range(1,22)
odds = to_21[::2]
middle_third = to_21[7:14:1]
14.   For loop:
my_list = [1,9,3,8,5,7]
for number in my_list:
    print 2*number
else:
    print “Well done”
The else block only executes if the for loop executes normally (ie there is no break causing the loop to terminate mid-way).
for loop with range():
n = [3, 5, 7]
def print_list(x):
    for i in range(0, len(x)):
        print x[i]
print_list(n)

for I in range(20) => 0 to 20
for I in range(1, 10) => 1 to 9
Need index with for each loop – use enumerate() built-in function:
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item
Iterate over 2 or more lists at once:
Zip() will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
    # Add your code here!
    print max(a,b)
Populate a list:
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50

15.   Dictionary:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
menu = {}
menu[‘Samosa’] = 1.60
del residents[‘Puffin’] => remove item from dictionary
menu[‘Samosa’] = 1.50

for key in residents
                print residents[key]

print residents.items() => returns dictionary as list of key/value pairs.
Print residents.keys() => list of all keys
Print residents.values() => list of all values
16.   While loop:
while count < 10:
                count += 1
else:
                print “Game over!”
17.   Print:
The , character after our printstatement means that our next printstatement keeps printing on the same line.
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

for key in d:
    # Your code here!
    print key, " ", d[key]
18.   Lambda: Anonymous function:
Python’s support for functional programming => meaning you are allowed to pass functions around just as if they were variables or values.

lambda x: x % 3 == 0

is same as:

def by_three(x):
    return x % 3 == 0

Usage: filter uses lamba expression below to print only those elements of the list that satisfy that return true for the lambda expression (or satisfy the condition divisible by 3).

my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list) => [0, 3, 6, 9, 12, 15]
19.   Bitwise:

print 5 >> 4  # Right Shift => 0
print 5 << 1  # Left Shift => 10
print 8 & 5   # Bitwise AND => 0
print 9 | 4   # Bitwise OR => 13
print 12 ^ 42 # Bitwise XOR => 38
print ~88     # Bitwise NOT => -89 (equivalent to adding 1 to the number and putting a – sign).

XOR => in-equality is true (0b1100 ^ 0b101010 => 0b100110)

In Python, you can write numbers in binary format by starting the number with 0b.

print 0b1 + 0b11 => 4

bin() – to binary (as string)
hex() – to hex
oct() – to octal

print bin(5) => 0b101
print hex(5) => 0x5
print oct(5) => 05

int(str, radix)  - any string (includes, binary/hex/octal with appropriate radix (2,16,8)) to int

int("110", 2) => 6
print int("0b100",2) => 4
print int(bin(5),2) => 5

20.   Classes:
An empty class:
class Animal(object):
    pass

pass – special python keyword for placeholder – in areas of code where python expects an expression.

class Triangle(object):
    number_of_sides = 3
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3

    def check_angles(self):
        if self.angle1 + self.angle2 + self.angle3 == 180:
            return True
        else:
            return False

my_triangle = Triangle(90, 30, 60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

class Equilateral(Triangle):
    angle = 60
    def __init__(self):
        self.angle1 = self.angle
        self.angle2 = self.angle
        self.angle3 = self.angle

class MyTriangle(Equilateral):
    def __init__(self, beauty):
        self.beauty = beauty
        self.angle1 = 70

my_triangle = MyTriangle(True)
print my_triangle.angle1 # angle1/2/3 not inherited from base class Triangle
print my_triangle.number_of_sides # member inherited from Triangle
print my_triangle.angle # member inherited from Equilateral

1.       object is base class from which all classes inherit (same as Java).
2.       Constructors are - __init__(self…)
3.       Self needs to be the first param for all member methods and constructors.
4.       Derived class constructor needs to initialize all base members that don’t have a default value.
5.       Derived class inherits all base class members that have default values (defined outside of base class’s constructor).

21.   File I/O:
my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10

f = open("output.txt", "w")

for item in my_list:
    f.write(str(item) + "\n")

f.close()

or

with open("text.txt", "w") as my_file:
                my_file.write("Success!")


with … as syntax is like try-with-resources in Java and it auto closes the file.

No comments:

Book notes: Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems, by Martin Kleppmann

My notes from the excellent book on how software has evolved to handle data from hierarchical databases to the NoSQL -  https://www.goodrea...