








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









CS107 Handout 35 Spring 2008 May 28, 2008
bash-3.2$ python Python 2.5.1 (r251:54863, Oct 5 2007, 21:08:09) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 4 + 15 19 >>> 8 / 2 * 7 28 >>> x = 12 >>> x ** 2 144 >>> y = 9 + 7 * x >>> y 93 >>> ^D bash-3.2$
True >>> "apple " == "bear" False >>> " apple " < " bear " < " candy cane " < " dill " True >>> x = y = 7 >>> x <= y and y <= x True >>> not x >= y False
>>> factorial(6) 720 >>> factorial(5) 120 >>> factorial(10) 3628800 >>> factorial(15) 1307674368000L >>> factorial(40) 815915283247897734345611269596115894272000000000L
>>> interjection = " ohplease " >>> interjection[2:6] 'plea' >>> interjection[4:] 'ease' >>> interjection[:2] 'oh' >>> interjection[:] 'ohplease' >>> interjection * 4 'ohpleaseohpleaseohpleaseohplease' >>> oldmaidsays = " pickme " + interjection * 3 >>> oldmaidsays 'pickmeohpleaseohpleaseohplease' >>> 'abcdefghijklmnop'[-5:] # negative indices count from the end! 'lmnop'
>>> streets[1:6] ['Noe', 'Sanchez', 'Church', 'Dolores', 'Van Ness'] >>> streets[:2] ['Castro', 'Noe'] >>> streets[5:5] []
>>> streets ['Castro', 'Noe', 'Sanchez', 'Church', 'Dolores', 'Van Ness', 'Folsom'] >>> streets[5:5] = ["Guerrero", "Valencia", "Mission"] >>> streets ['Castro', 'Noe', 'Sanchez', 'Church', 'Dolores', 'Guerrero', 'Valencia', 'Mission', 'Van Ness', 'Folsom'] >>> streets[0:1] = ["Eureka", "Collingswood", "Castro"] >>> streets ['Eureka', 'Collingswood', 'Castro', 'Noe', 'Sanchez', 'Church', 'Dolores', 'Guerrero', 'Valencia', 'Mission', 'Van Ness', 'Folsom'] >>> streets.append("Harrison") >>> streets ['Eureka', 'Collingswood', 'Castro', 'Noe', 'Sanchez', 'Church', 'Dolores', 'Guerrero', 'Valencia', 'Mission', 'Van Ness', 'Folsom', 'Harrison']
>>> prop = ["355 Noe Street", 3, 1.5, 2460, [[1988, 385000],[2004, 1 380000]]] >>> print("The house at %s was built in %d." % (prop[0], prop[4][0][0]) The house at 355 Noe Street was built in 1988.
>>> cto = ("Will Shulman", 154000, "BSCS Stanford, 1997") >>> cto[0] 'Will Shulman' >>> cto[2] 'BSCS Stanford, 1997' >>> cto[1:2] (154000,) >>> cto[0:2] ('Will Shulman', 154000) >>> cto[1:2] = 158000
Traceback (most recent call last): File "", line 1, in? TypeError: object doesn't support slice assignment
def gatherDivisors(num): """Synthesizes a list of all the positive numbers that evenly divide into the specified num.""" divisors = [] for d in xrange(1, num/2 + 1): if (num % d == 0): divisors.append(d) return divisors
#!/usr/bin/env python
import sys def numDigits(num): """Returns the number of digits making up a number, not counting leading zeroes, except for the number 0 itself.""" if (num == 0): return 1 digitCount = 0 while (num > 0): digitCount += 1 num /= 10 return digitCount def isNarcissistic(num): """Returns True if and only if the number is a narcissistic number.""" originalNum = num total = 0 exp = numDigits(num) while (num > 0): digit = num % 10 num /= 10 total += digit ** exp return total == originalNum def listNarcissisticNumbers(numNeeded): """Searches for an prints out the first 'numNeeded' narcissistic numbers.""" numFound = 0; numToConsider = 0; print "Here are the first %d narcissistic numbers." % numNeeded while (numFound < numNeeded): if (isNarcissistic(numToConsider)): numFound += 1 print numToConsider numToConsider += 1 print "Done!" def getNumberNeeded(): """Parses the command line arguments to the extent necessary to determine how many narcissistic numbers the user would like to print.""" numNeeded = 15; # this is the default number if len(sys.argv) > 1: try: numNeeded = int(sys.argv[1]) except ValueError: print "Non-integral argument encountered... using default." return numNeeded listNarcissisticNumbers(getNumberNeeded()) Required so that we can parse the command line via variables defined by the sys module. The slash-bang is usually the first line of a script, and it tells us what environment to run the script in. The encoding thing is optional, but standard. One-liner slave expressions can be on the same line as their owner, like this. The equivalent of System.out.println, but with printf’s substitution strategy. The exposed % marks the beginning of the expressions that should fill in the %d and %s placeholders. No ++ An exposed function call, which gets evaluated as the script runs. This is effectively your main program, except you get to name your top-level function in Python.
def quicksort(sequence): """Classic implementation of quicksort using list comprehensions and assuming the traditional relational operators work. The primary weakness of this particular implementation of quicksort is that it makes two passes over the sequence instead of just one.""" if (len(sequence) == 0): return sequence front = quicksort([le for le in sequence[1:] if le <= sequence[0]]) back = quicksort([gt for gt in sequence[1:] if gt > sequence[0]]) return front + [sequence[0]] + back >>> from quicksort import quicksort >>> quicksort([5, 3, 6, 1, 2, 9]) [1, 2, 3, 5, 6, 9] >>> quicksort(["g", "b", "z", "k", "e", "a", "y", "s"]) ['a', 'b', 'e', 'g', 'k', 's', 'y', 'z']
>>> [(x, y) for x in xrange(1, 3) for y in xrange(4, 8)] [(1, 4), (1, 5), (1, 6), (1, 7), (2, 4), (2, 5), (2, 6), (2, 7)] >>> [(x, y, z) for x in range(1, 5) for y in range(1, 5) for z in range(1, 6) if x < y <= z] [(1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 3), (1, 3, 4), (1, 3, 5), (1, 4, 4), (1, 4, 5), (2, 3, 3), (2, 3, 4), (2, 3, 5), (2, 4, 4), (2, 4, 5), (3, 4, 4), (3, 4, 5)]
jerry> find.py /usr/class/cs107/submissions/hw4/Jerry/ rss-news-search.c /usr/class/cs107/submissions/hw4/Jerry/izaak-1/rss-news-search.c /usr/class/cs107/submissions/hw4/Jerry/ajlin-1/rss-news-search.c /usr/class/cs107/submissions/hw4/Jerry/taijin-1/rss-news-search.c /usr/class/cs107/submissions/hw4/Jerry/sholbert-1/rss-news-search.c /usr/class/cs107/submissions/hw4/Jerry/hmooers-1/rss-news-search.c /usr/class/cs107/submissions/hw4/Jerry/msmissyw-1/rss-news-search.c /usr/class/cs107/submissions/hw4/Jerry/jorelman-1/rss-news-search.c /usr/class/cs107/submissions/hw4/Jerry/jdlong-1/rss-news-search.c
"/usr/class/cs107/bin/submit"
#!/usr/bin/env python
from xml.dom import * from xml.dom.minidom import parse from urllib2 import urlopen from sys import argv
def listAllArticles(rssURL): """Lists all of the titles of the articles identified by the specified feed""" conn = urlopen(rssURL) xmldoc = parse(conn) items = xmldoc.getElementsByTagName("item") for item in items: titles = item.getElementsByTagName("title") title = titles[0].childNodes[0].nodeValue print("Article Title: %s" % title.encode('utf-8')) def extractFeedName(): """Pulls the URL from the command line if there is one, but otherwise uses a default.""" defaultFeedURL = "http://feeds.chicagotribune.com/chicagotribune/news/" feedURL = defaultFeedURL if (len(argv) == 2): feedURL = argv[1] return feedURL listAllArticles(extractFeedName())
>>> primaryHome = {} # initialize empty dictionary, add stuff line by line >>> primaryHome["phone"] = "609- 786 - 06xx" >>> primaryHome["house-type"] = "rancher" >>> primaryHome["address"] = {} >>> primaryHome["address"]["number"] = 2210 >>> primaryHome["address"]["street"] = "Hope Lane" >>> primaryHome["address"]["city"] = "Cinnaminson" >>> primaryHome["address"]["state"] = "New Jersey" >>> primaryHome["address"]["zip"] = "08077" >>> primaryHome["num-bedrooms"] = 3 >>> primaryHome["num-bathrooms"] = 1. >>> primaryHome {'num-bathrooms': 1.5, 'phone': '609- 786 - 06xx', 'num-bedrooms': 3, 'house- type': 'rancher', 'address': {'city': 'Cinnaminson', 'state': 'New Jersey', 'street': 'Hope Lane', 'number': 2210, 'zip': '08077'}} >>> primaryHome["address"]["street"] 'Hope Lane'
sys.stdout.write('.) ') expand('') sys.stdout.write('\n') generateRandomSentences(3)
bash-3.2$ rsg.py 1.) The slugs portend like waves tonight. 2.) The big yellow flowers portend like big yellow flowers tonight. 3.) The big yellow flowers portend like waves tonight. bash-3.2$ rsg.py 1.) The big yellow flowers sigh warily tonight. 2.) The slugs sigh grumpily tonight. 3.) The slugs portend like big yellow flowers tonight. bash-3.2$ rsg.py 1.) The waves portend like waves tonight. 2.) The big yellow flowers sigh grumpily tonight. 3.) The slugs sigh warily tonight.
from bisect import bisect class lexicon: def init(self, filename = 'words'): """Constructs a raw lexicon by reading in the presumably alphabetized list of words in the specified file. No error checking is performed on the file, though.""" infile = open(filename, 'r') words = infile.readlines() # retains newlines self.__words = map(lambda w: w.rstrip(), words) def containsWord(self, word): """Implements traditional binary search on the lexicon to see if the specified word is present.""" return self.words[bisect(self.words, word) - 1] == word def wordContainsEverything(self, word, characterset): """Returns True if and only if the specified word contains every single character in the specified character set.""" for i in range(len(characterset)): if (word.find(characterset[i]) < 0): return False return True def listAllWordsContaining(self, characterset): """Brute force lists all of the words in the lexicon that contain each and every character in the character set.""" matchingWords = [] for word in self.words: if (self.wordContainsEverything(word, characterset)): matchingWords.append(word) if (len(matchingWords) == 0): print "We didn't find any words that contained all those characters." print "Try a less constraining character set." return print "Listing all words with the letters "%s"" % characterset print "" for word in matchingWords: print "\t%s" % word print "" The init method is the Python equivalent of a constructor. It’s optional, but since there’s typically at least one attribute that needs to be initialized (else why do we have a class?), it’s unusual to not have a constructor for any meaningful object type. Here’s a normal method. Note that all methods (and the special init method) all take an exposed self pointer.