Python Examples Set 2

Python Examples Set 2

# Output
print 'an Ashish Ranjan presentation'

@IDLE
an Ashish Ranjan presentation
>>> 



# Input, assignment name = raw_input('What is your name? '), print 'Hi, %s.' % name @IDLE What is your name? Ashish Ranjan Hi, Ashish Ranjan. >>>

# For loop, built-in enumerate function, new style formatting phrase = ['an', 'Ashish', 'Ranjan', 'presentation'] for i, word in enumerate(phrase): print "iteration {iteration} is {word}".format(iteration=i, word=word) @IDLE iteration 0 is an iteration 1 is Ashish iteration 2 is Ranjan iteration 3 is presentation >>>

# Fibonacci, tuple assignment parents, babies = (1, 1) while babies < 100: print babies, " ", parents, babies = (babies, parents + babies) @IDLE 1 2 3 5 8 13 21 34 55 89 >>>

# Functions def func(word): print word, func('an') func('Ashish') func('Ranjan') func('presentation') @IDLE an Ashish Ranjan presentation >>>

# Import, regular expressions # +91 9916075509 # +91-9916075509 # +919916075509 # 9916075509 # ^ - beginning of the string # (\+91[\-\s]?)? - matches optional ISD code with optional - or whitespace inbetween # [89] - last I checked Indian mobile numbers begin with 8 or 9 # \d{9} - followed by 9 digits ( total of 10 ) # $ - end of string import re for test_string in ['+91-8092520647', 'ILL-EGAL']: if re.match(r'^(\+91[\-\s]?)?[89]\d{9}$', test_string): print test_string, 'is a valid IN local phone number' else: print test_string, 'rejected' @IDLE +91-8092520647 is a valid IN local phone number ILL-EGAL rejected >>>

# Dictionaries, generator expressions prices = {'apple': 0.40, 'banana': 0.50} my_purchase = { 'apple': 1, 'banana': 6 } grocery_bill = sum(prices[fruit] * my_purchase[fruit] for fruit in my_purchase) print 'I owe the grocer $%.2f' % grocery_bill @IDLE I owe the grocer $3.40 >>>

# Command line arguments, exception handling import sys try: total = sum(int(arg) for arg in sys.argv[1:]) print 'sum =', total except ValueError: print 'Please supply integer arguments' @cmd F:\Python Programs\set 2>python example1.py an Ashish Ranjan presentation Please supply integer arguments F:\Python Programs\set 2>python example1.py 2016 sum = 2016 F:\Python Programs\set 2>python example1.py 2016 23 sum = 2039 F:\Python Programs\set 2>python example1.py 2016 23 1 sum = 2040 F:\Python Programs\set 2>

# glob supports Unix style pathname extensions import glob python_files = glob.glob('*.txt') for file_name in sorted(python_files): print ' ------' + file_name with open(file_name) as f: for line in f: print ' ' + line.rstrip() print @IDLE ------text1.txt an Ashish Ranjan presentation ------text2.txt an INDIAN >>>

# Time, conditionals, from..import, for..else from time import localtime activities = {8: 'Sleeping', 9: 'Commuting', 17: 'Working', 18: 'Commuting', 20: 'Eating', 22: 'Resting', 23: 'Dreaming'} time_now = localtime() hour = time_now.tm_hour for activity_time in sorted(activities.keys()): if hour < activity_time: print activities[activity_time] break else: print 'Unknown, AFK (AWAY FROM KEYBOARD) or sleeping!' print time_now @IDLE Dreaming time.struct_time(tm_year=2016, tm_mon=4, tm_mday=27, tm_hour=22, tm_min=51, tm_sec=33, tm_wday=2, tm_yday=118, tm_isdst=0)

# Triple-quoted strings, while loop REFRAIN = ''' %d bottles of beer on the wall, %d bottles of beer, take one down, pass it around, %d bottles of beer on the wall! ''' bottles_of_beer = 5 while bottles_of_beer > 1: print REFRAIN % (bottles_of_beer, bottles_of_beer, bottles_of_beer - 1) bottles_of_beer -= 1 @IDLE 5 bottles of beer on the wall, 5 bottles of beer, take one down, pass it around, 4 bottles of beer on the wall! 4 bottles of beer on the wall, 4 bottles of beer, take one down, pass it around, 3 bottles of beer on the wall! 3 bottles of beer on the wall, 3 bottles of beer, take one down, pass it around, 2 bottles of beer on the wall! 2 bottles of beer on the wall, 2 bottles of beer, take one down, pass it around, 1 bottles of beer on the wall!

#Classes class BankAccount(object): def __init__(self, initial_balance=0): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def overdrawn(self): return self.balance < 0 my_account = BankAccount(15) my_account.withdraw(5) print my_account.balance #IDLE 10 >>>

# Unit testing with unittest import unittest def median(pool): copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[(size - 1) / 2] else: return (copy[size/2 - 1] + copy[size/2]) / 2 class TestMedian(unittest.TestCase): def testMedian(self): self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7) if __name__ == '__main__': unittest.main() @IDLE . ---------------------------------------------------------------------- Ran 1 test in 0.007s OK

# Doctest-based testing def median(pool): '''Statistical median to demonstrate doctest. >>> median([2, 9, 9, 7, 9, 2, 4, 5, 8]) 7 ''' copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[(size - 1) / 2] else: return (copy[size/2 - 1] + copy[size/2]) / 2 if __name__ == '__main__': import doctest doctest.testmod() @cmd F:\Python Programs\set 2>python example1.py -v Trying: median([2, 9, 9, 7, 9, 2, 4, 5, 8]) Expecting: 7 ok 1 items had no tests: __main__ 1 items passed all tests: 1 tests in __main__.median 1 tests in 2 items. 1 passed and 0 failed. Test passed. F:\Python Programs\set 2>

# itertools from itertools import groupby lines = ''' an Ashish Ranjan presentation from INDIA This is year 2016. '''.splitlines() # Use itertools.groupby and bool to return groups of # consecutive lines that either have content or don't. for has_chars, frags in groupby(lines, bool): if has_chars: print ' '.join(frags) @IDLE an Ashish Ranjan presentation from INDIA This is year 2016.

# csv module, tuple unpacking, cmp() built-in import csv # write stocks data as comma-separated values writer = csv.writer(open('stocks.csv', 'wb', buffering=0)) writer.writerows([ ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09), ('YHOO', 'Yahoo! Inc.', 27.38, 0.33, 1.22), ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49) ]) # read stocks data, print status messages stocks = csv.reader(open('stocks.csv', 'rb')) status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'} for ticker, name, price, change, pct in stocks: status = status_labels[cmp(float(change), 0.0)] print '%s is %s (%s%%)' % (name, status, pct) @IDLE Google, Inc. is up (0.09%) Yahoo! Inc. is up (1.22%) CNET Networks, Inc. is down (-1.49%)

# 8-Queens Problem (recursion) # The eight queens puzzle is an example of the more general n-queens problem of placing n queens on an n*n chessboard, # where solutions exist for all natural numbers n with the exception of n=2 and n=3. # The problem can be quite computationally expensive as there are 4,426,165,368 (i.e., 64C8) possible arrangements of eight queens on an 8*8 board, # but only 92 solutions. # If solutions that differ only by symmetry operations (rotations and reflections) of the board are counted as one, the puzzle has 12 fundamental solutions. BOARD_SIZE = 8 def under_attack(col, queens): left = right = col for r, c in reversed(queens): left, right = left - 1, right + 1 if c in (left, col, right): return True return False def solve(n): if n == 0: return [[]] smaller_solutions = solve(n - 1) return [solution+[(n,i+1)] for i in xrange(BOARD_SIZE) for solution in smaller_solutions if not under_attack(i+1, solution)] i, j = 0, 0 for answer in solve(BOARD_SIZE): print answer @IDLE [(1, 4), (2, 2), (3, 7), (4, 3), (5, 6), (6, 8), (7, 5), (8, 1)] [(1, 5), (2, 2), (3, 4), (4, 7), (5, 3), (6, 8), (7, 6), (8, 1)] [(1, 3), (2, 5), (3, 2), (4, 8), (5, 6), (6, 4), (7, 7), (8, 1)] [(1, 3), (2, 6), (3, 4), (4, 2), (5, 8), (6, 5), (7, 7), (8, 1)] [(1, 5), (2, 7), (3, 1), (4, 3), (5, 8), (6, 6), (7, 4), (8, 2)] [(1, 4), (2, 6), (3, 8), (4, 3), (5, 1), (6, 7), (7, 5), (8, 2)] [(1, 3), (2, 6), (3, 8), (4, 1), (5, 4), (6, 7), (7, 5), (8, 2)] [(1, 5), (2, 3), (3, 8), (4, 4), (5, 7), (6, 1), (7, 6), (8, 2)] [(1, 5), (2, 7), (3, 4), (4, 1), (5, 3), (6, 8), (7, 6), (8, 2)] [(1, 4), (2, 1), (3, 5), (4, 8), (5, 6), (6, 3), (7, 7), (8, 2)] [(1, 3), (2, 6), (3, 4), (4, 1), (5, 8), (6, 5), (7, 7), (8, 2)] [(1, 4), (2, 7), (3, 5), (4, 3), (5, 1), (6, 6), (7, 8), (8, 2)] [(1, 6), (2, 4), (3, 2), (4, 8), (5, 5), (6, 7), (7, 1), (8, 3)] [(1, 6), (2, 4), (3, 7), (4, 1), (5, 8), (6, 2), (7, 5), (8, 3)] [(1, 1), (2, 7), (3, 4), (4, 6), (5, 8), (6, 2), (7, 5), (8, 3)] [(1, 6), (2, 8), (3, 2), (4, 4), (5, 1), (6, 7), (7, 5), (8, 3)] [(1, 6), (2, 2), (3, 7), (4, 1), (5, 4), (6, 8), (7, 5), (8, 3)] [(1, 4), (2, 7), (3, 1), (4, 8), (5, 5), (6, 2), (7, 6), (8, 3)] [(1, 5), (2, 8), (3, 4), (4, 1), (5, 7), (6, 2), (7, 6), (8, 3)] [(1, 4), (2, 8), (3, 1), (4, 5), (5, 7), (6, 2), (7, 6), (8, 3)] [(1, 2), (2, 7), (3, 5), (4, 8), (5, 1), (6, 4), (7, 6), (8, 3)] [(1, 1), (2, 7), (3, 5), (4, 8), (5, 2), (6, 4), (7, 6), (8, 3)] [(1, 2), (2, 5), (3, 7), (4, 4), (5, 1), (6, 8), (7, 6), (8, 3)] [(1, 4), (2, 2), (3, 7), (4, 5), (5, 1), (6, 8), (7, 6), (8, 3)] [(1, 5), (2, 7), (3, 1), (4, 4), (5, 2), (6, 8), (7, 6), (8, 3)] [(1, 6), (2, 4), (3, 1), (4, 5), (5, 8), (6, 2), (7, 7), (8, 3)] [(1, 5), (2, 1), (3, 4), (4, 6), (5, 8), (6, 2), (7, 7), (8, 3)] [(1, 5), (2, 2), (3, 6), (4, 1), (5, 7), (6, 4), (7, 8), (8, 3)] [(1, 6), (2, 3), (3, 7), (4, 2), (5, 8), (6, 5), (7, 1), (8, 4)] [(1, 2), (2, 7), (3, 3), (4, 6), (5, 8), (6, 5), (7, 1), (8, 4)] [(1, 7), (2, 3), (3, 1), (4, 6), (5, 8), (6, 5), (7, 2), (8, 4)] [(1, 5), (2, 1), (3, 8), (4, 6), (5, 3), (6, 7), (7, 2), (8, 4)] [(1, 1), (2, 5), (3, 8), (4, 6), (5, 3), (6, 7), (7, 2), (8, 4)] [(1, 3), (2, 6), (3, 8), (4, 1), (5, 5), (6, 7), (7, 2), (8, 4)] [(1, 6), (2, 3), (3, 1), (4, 7), (5, 5), (6, 8), (7, 2), (8, 4)] [(1, 7), (2, 5), (3, 3), (4, 1), (5, 6), (6, 8), (7, 2), (8, 4)] [(1, 7), (2, 3), (3, 8), (4, 2), (5, 5), (6, 1), (7, 6), (8, 4)] [(1, 5), (2, 3), (3, 1), (4, 7), (5, 2), (6, 8), (7, 6), (8, 4)] [(1, 2), (2, 5), (3, 7), (4, 1), (5, 3), (6, 8), (7, 6), (8, 4)] [(1, 3), (2, 6), (3, 2), (4, 5), (5, 8), (6, 1), (7, 7), (8, 4)] [(1, 6), (2, 1), (3, 5), (4, 2), (5, 8), (6, 3), (7, 7), (8, 4)] [(1, 8), (2, 3), (3, 1), (4, 6), (5, 2), (6, 5), (7, 7), (8, 4)] [(1, 2), (2, 8), (3, 6), (4, 1), (5, 3), (6, 5), (7, 7), (8, 4)] [(1, 5), (2, 7), (3, 2), (4, 6), (5, 3), (6, 1), (7, 8), (8, 4)] [(1, 3), (2, 6), (3, 2), (4, 7), (5, 5), (6, 1), (7, 8), (8, 4)] [(1, 6), (2, 2), (3, 7), (4, 1), (5, 3), (6, 5), (7, 8), (8, 4)] [(1, 3), (2, 7), (3, 2), (4, 8), (5, 6), (6, 4), (7, 1), (8, 5)] [(1, 6), (2, 3), (3, 7), (4, 2), (5, 4), (6, 8), (7, 1), (8, 5)] [(1, 4), (2, 2), (3, 7), (4, 3), (5, 6), (6, 8), (7, 1), (8, 5)] [(1, 7), (2, 1), (3, 3), (4, 8), (5, 6), (6, 4), (7, 2), (8, 5)] [(1, 1), (2, 6), (3, 8), (4, 3), (5, 7), (6, 4), (7, 2), (8, 5)] [(1, 3), (2, 8), (3, 4), (4, 7), (5, 1), (6, 6), (7, 2), (8, 5)] [(1, 6), (2, 3), (3, 7), (4, 4), (5, 1), (6, 8), (7, 2), (8, 5)] [(1, 7), (2, 4), (3, 2), (4, 8), (5, 6), (6, 1), (7, 3), (8, 5)] [(1, 4), (2, 6), (3, 8), (4, 2), (5, 7), (6, 1), (7, 3), (8, 5)] [(1, 2), (2, 6), (3, 1), (4, 7), (5, 4), (6, 8), (7, 3), (8, 5)] [(1, 2), (2, 4), (3, 6), (4, 8), (5, 3), (6, 1), (7, 7), (8, 5)] [(1, 3), (2, 6), (3, 8), (4, 2), (5, 4), (6, 1), (7, 7), (8, 5)] [(1, 6), (2, 3), (3, 1), (4, 8), (5, 4), (6, 2), (7, 7), (8, 5)] [(1, 8), (2, 4), (3, 1), (4, 3), (5, 6), (6, 2), (7, 7), (8, 5)] [(1, 4), (2, 8), (3, 1), (4, 3), (5, 6), (6, 2), (7, 7), (8, 5)] [(1, 2), (2, 6), (3, 8), (4, 3), (5, 1), (6, 4), (7, 7), (8, 5)] [(1, 7), (2, 2), (3, 6), (4, 3), (5, 1), (6, 4), (7, 8), (8, 5)] [(1, 3), (2, 6), (3, 2), (4, 7), (5, 1), (6, 4), (7, 8), (8, 5)] [(1, 4), (2, 7), (3, 3), (4, 8), (5, 2), (6, 5), (7, 1), (8, 6)] [(1, 4), (2, 8), (3, 5), (4, 3), (5, 1), (6, 7), (7, 2), (8, 6)] [(1, 3), (2, 5), (3, 8), (4, 4), (5, 1), (6, 7), (7, 2), (8, 6)] [(1, 4), (2, 2), (3, 8), (4, 5), (5, 7), (6, 1), (7, 3), (8, 6)] [(1, 5), (2, 7), (3, 2), (4, 4), (5, 8), (6, 1), (7, 3), (8, 6)] [(1, 7), (2, 4), (3, 2), (4, 5), (5, 8), (6, 1), (7, 3), (8, 6)] [(1, 8), (2, 2), (3, 4), (4, 1), (5, 7), (6, 5), (7, 3), (8, 6)] [(1, 7), (2, 2), (3, 4), (4, 1), (5, 8), (6, 5), (7, 3), (8, 6)] [(1, 5), (2, 1), (3, 8), (4, 4), (5, 2), (6, 7), (7, 3), (8, 6)] [(1, 4), (2, 1), (3, 5), (4, 8), (5, 2), (6, 7), (7, 3), (8, 6)] [(1, 5), (2, 2), (3, 8), (4, 1), (5, 4), (6, 7), (7, 3), (8, 6)] [(1, 3), (2, 7), (3, 2), (4, 8), (5, 5), (6, 1), (7, 4), (8, 6)] [(1, 3), (2, 1), (3, 7), (4, 5), (5, 8), (6, 2), (7, 4), (8, 6)] [(1, 8), (2, 2), (3, 5), (4, 3), (5, 1), (6, 7), (7, 4), (8, 6)] [(1, 3), (2, 5), (3, 2), (4, 8), (5, 1), (6, 7), (7, 4), (8, 6)] [(1, 3), (2, 5), (3, 7), (4, 1), (5, 4), (6, 2), (7, 8), (8, 6)] [(1, 5), (2, 2), (3, 4), (4, 6), (5, 8), (6, 3), (7, 1), (8, 7)] [(1, 6), (2, 3), (3, 5), (4, 8), (5, 1), (6, 4), (7, 2), (8, 7)] [(1, 5), (2, 8), (3, 4), (4, 1), (5, 3), (6, 6), (7, 2), (8, 7)] [(1, 4), (2, 2), (3, 5), (4, 8), (5, 6), (6, 1), (7, 3), (8, 7)] [(1, 4), (2, 6), (3, 1), (4, 5), (5, 2), (6, 8), (7, 3), (8, 7)] [(1, 6), (2, 3), (3, 1), (4, 8), (5, 5), (6, 2), (7, 4), (8, 7)] [(1, 5), (2, 3), (3, 1), (4, 6), (5, 8), (6, 2), (7, 4), (8, 7)] [(1, 4), (2, 2), (3, 8), (4, 6), (5, 1), (6, 3), (7, 5), (8, 7)] [(1, 6), (2, 3), (3, 5), (4, 7), (5, 1), (6, 4), (7, 2), (8, 8)] [(1, 6), (2, 4), (3, 7), (4, 1), (5, 3), (6, 5), (7, 2), (8, 8)] [(1, 4), (2, 7), (3, 5), (4, 2), (5, 6), (6, 1), (7, 3), (8, 8)] [(1, 5), (2, 7), (3, 2), (4, 6), (5, 3), (6, 1), (7, 4), (8, 8)] >>>

# Prime numbers sieve w/fancy generators import itertools def iter_primes(): # an iterator of all numbers between 2 and +infinity numbers = itertools.count(2) # generate primes forever while True: # get the first number from the iterator (always a prime) prime = numbers.next() yield prime # this code iteratively builds up a chain of # filters...slightly tricky, but ponder it a bit numbers = itertools.ifilter(prime.__rmod__, numbers) for p in iter_primes(): if p > 100: break print p @IDLE 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

# XML/HTML parsing (using Python 2.5 or third-party library) dinner_recipe = ''' <html> <body> <table> <tr><th>amt</th><th>unit</th><th>item</th></tr> <tr><td>24</td><td>slices</td><td>baguette</td></tr> <tr><td>2+</td<<td>tbsp</td><td>olive oil</td></tr> <tr><td>1</td><td>cup</td><td>tomatoes</td></tr> <tr><td>1</td><td>jar</td><td>pesto</td></tr> </table> </body> </html>''' # In Python 2.5 or from http://effbot.org/zone/element-index.htm import xml.etree.ElementTree as etree tree = etree.fromstring(dinner_recipe) # For invalid HTML use http://effbot.org/zone/element-soup.htm # import ElementSoup, StringIO # tree = ElementSoup.parse(StringIO.StringIO(dinner_recipe)) pantry = set(['olive oil', 'pesto']) for ingredient in tree.getiterator('tr'): amt, unit, item = ingredient if item.tag == "td" and item.text not in pantry: print "%s: %s %s" % (item.text, amt.text, unit.text) @IDLE baguette: 24 slices tomatoes: 1 cup

# 8-Queens Problem (define your own exceptions) BOARD_SIZE = 8 class BailOut(Exception): pass def validate(queens): left = right = col = queens[-1] for r in reversed(queens[:-1]): left, right = left-1, right+1 if r in (left, col, right): raise BailOut def add_queen(queens): for i in range(BOARD_SIZE): test_queens = queens + [i] try: validate(test_queens) if len(test_queens) == BOARD_SIZE: return test_queens else: return add_queen(test_queens) except BailOut: pass raise BailOut queens = add_queen([]) print queens print "\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) for q in queens) @IDLE [0, 4, 7, 5, 2, 6, 1, 3] Q . . . . . . . . . . . Q . . . . . . . . . . Q . . . . . Q . . . . Q . . . . . . . . . . . Q . . Q . . . . . . . . . Q . . . .

import random guesses_made = 0 name = raw_input('Hello! What is your name?\n') number = random.randint(1, 20) print 'Well, {0}, I am thinking of a number between 1 and 20.'.format(name) while guesses_made < 6: guess = int(raw_input('Take a guess: ')) guesses_made += 1 if guess < number: print 'Your guess is too low.' if guess > number: print 'Your guess is too high.' if guess == number: break if guess == number: print 'Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made) else: print 'Nope. The number I was thinking of was {0}'.format(number) @IDLE Hello! What is your name? Ashish Ranjan Well, Ashish Ranjan, I am thinking of a number between 1 and 20. Take a guess: 15 Your guess is too high. Take a guess: 10 Your guess is too low. Take a guess: 12 Your guess is too low. Take a guess: 14 Good job, Ashish Ranjan! You guessed my number in 4 guesses!