Thursday, September 02, 2010

Python Cheat Sheet

I've been playing around with python over the last few days. It's really easy to use and I've written the following cheat sheet so that I don't forget how to use it:

Collections:

###################### TUPLE - immutable list
rgb = ("red", "green", "blue")

assert len(rgb) == 3
assert min(rgb) == "blue"
assert max(rgb) == "red"

#find the last element
assert rgb[len(rgb) - 1] == "blue"

assert "red" in rgb
assert "yellow" not in rgb

#slice the list [1,3)
rgb[1:3] #('green', 'blue')

#concatenate twice
rgb * 2

#iterate over list
for e in rgb:
 print e

###################### LIST - mutable list
colors = ["black", "white"]
assert len(colors) == 2

#add an element
colors.append("green")
assert len(colors) == 3
assert colors[2] == "green"

#remove an element
colors.remove("white")
assert "white" not in colors

colors.append("green")

#count occurrences of an element
assert colors.count("green") == 2

#return first index of value
assert colors.index("black") == 0

#insert element
colors.insert(1, "orange")
assert colors.index("orange") == 1

#remove the last element
e = colors.pop()
assert e == "green"

#replace a slice
colors[1:3] = ["red"];

colors.reverse()
colors.sort()

###################### SET
l = ["a", "b", "a", "c"]
assert len(set(l)) == 3

###################### DICTIONARY- mappings

dict = {"alice":22, "bob":20}
assert dict.get("alice") == 22

#add an element
dict["charlie"] = 25
assert dict.get("charlie") == 25

#get list of keys
assert len(dict.keys()) == 3

#get list of values
assert len(dict.values()) == 3

#check for key
assert dict.has_key("alice")
Loops:
for i in range(1, 10, 2):
    print i

while True:
    print 1
    break
Methods:
Printing out the factorial of a number.
def factorial(n):
    """prints factorial of n using recursion."""
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print factorial(4)
Classes:
class Person:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def equals(self, p):
        return isinstance(p, Person) and \
               self.name == p.name and \
               self.age == p.age


    def toString(self):
        return "name: %s, age: %s" % (self.name, self.age)


p = Person("Bob", 20)
q = Person("Charlie", 20)
assert p.equals(p)
assert p.equals(q)==False
print p.toString()
Read user input:
string = raw_input("Enter your name: ")
number = input("Enter a number:")
File I/O:
#write to file
filename = "C:/temp/test.txt"
f = file(filename, "w")
f.write("HELLO WORLD\nHELLO WORLD")
f.close()

#open a file in read-mode
f = file(filename, "r")

#read all lines into a list in one go
assert len(f.readlines()) == 2

#print out current position
print f.tell()

#go to beginning of file
f.seek(0)

#read file line by line with auto-cleanup
with open("C:\\temp\hello.wsdl") as f:
    for line in f:
        print line
Pickling (Serialisation):
#pickling
f = file("C:\\temp\dictionary.txt", 'w')
dict = {"alice":22, "bob":20}
import pickle
pickle.dump(dict, f)
f.close()

#unpickling
f = file("C:\\temp\dictionary.txt", 'r')
obj = pickle.load(f)
f.close()
assert obj["alice"] == 22
assert obj["bob"] == 20
Exception handling:
try:
    i = int("Hello")
except ValueError:
    i = -1
finally:
    print "finally"


#creating a custom exception class
from repr import repr

class MyException(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

try:
    raise MyException(2*2)
except MyException as e:
    print 'My exception occurred, value:', e.value
Lambdas:
def make_incrementor (n):
    return lambda x: x + n

f = make_incrementor(2)
print f(42)

print map(lambda x: x % 2, range(10))

2 comments:

  1. Anonymous3:05 PM

    Good one dude..

    Can you please tell me whats the best way to read and start coding by reading Language API or any other API?

    http://stackoverflow.com/questions/3734528/how-to-use-api-documentation

    ReplyDelete
  2. Anonymous5:02 PM

    Thank you very much!!!

    ReplyDelete