Friday, September 11, 2015

global variables in python

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print globvar     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

word count using dictionary

counts = {}
for w in words:
    counts[w] = counts.get(w,0) + 1

count letters using dictionary get method

def countLetters(word):
    letterdict = {}
    for letter in word:
        letterdict[letter] = letterdict.get(letter, 0) + 1
    return letterdict

Find duplicates and store them in list

a= [1,2,3,2,1,5,6,5,5,5]
d = {}
for elem in a:
    if elem in d:
        d[elem] += 1
    else:
        d[elem] = 1

print d

print directory contents

import os

def file_list(dir):
    basedir = dir
    subdir_list = []
    for item in os.listdir(dir):
        fullpath = os.path.join(basedir,item)
        if os.path.isdir(fullpath):
            subdir_list.append(fullpath)
        else:
            print fullpath

    for d in subdir_list:
        file_list(d)

file_list('/dir')

Bubble sort in Python

def bubble_sort(items): """ Implementation of bubble sort """ for i in range(len(items)): for j in range(len(items)-1-i): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j]

Exceptions: try,catch and finally in Python

# A finally block is ALWAYS run, even if you return before it

def getkids():
        try:
                val = int(raw_input("how many kids have you? "))
        except StandardError, e:
                print "Error - ",e
                return "yer wot?"
        finally:
                print "T time"
        print val
        return val

getkids()
getkids()
getkids()