Python Documentation
Last updated
Last updated
: enum class to represent possible cell states
: Board class to represent the game board
: Represents a point in 2-D space. attributes: x, y
: Represents a rectangle. attributes: width, height, corner.
: Represents a standard playing card. Attributes: suit: integer 0-3 rank: integer 1-13
: Represents a deck of cards. Attributes: cards: list of Card objects.
: Represents a hand of playing cards.
: Represents the time of day. attributes: hour, minute, second
: Encapsulates the statistical summary of a text.
: Represents a point in 2-D space. attributes: x, y
:
: Represents the time of day. attributes: hour, minute, second
: Represents a poker hand.
: A simple implementation of a map using a list of tuples where each tuple is a key-value pair.
: A faster implementation of a map using a list of LinearMaps and the built-in function hash() to determine which LinearMap to put each key into.
My own function source code inspection function Filters out any print statements and input statements
fname
function which takes a list and returns two halves
al
merge generates a new sorted list containing all elements contained in both sorted lists
A
B
sorts the list using the mergesort algorithm
alist
In IPython, you have the very convenient "func"?? which will inspect the source code (http://j.mp/inspectThis) My own function source code inspection function Filters out any print statements and input statements
fname
Pure implementation of the selection sort algorithm in Python
collection:
some mutable ordered collection with heterogeneous comparable items inside
collection
swap two elements in a list
alist
ai
bi
alist
i
hlist
alist
alist
alist
alist
function returns the index of the minimum value in the sublist alist[i:]
alist
i
Authors: kgashok
circulate between three variables, three times
a
is a integer
b
is a integer
c
is a integer
Authors: kgashok
circulate 'n' elements in a list, n times
alist
contains the 'n' elements
Authors: kgashok
check whether a sequence is palindromic using unpacking
aseq
is a sequence, for e.g. string or list
Authors: kgashok
check for palindrome using unpacking, recursively
aseq
is a sequence of elements, string or list
Authors: kgashok
check for palindrome using slicing, recursively
aseq
is a sequence of elements, string or list
first
is first element in seq
None
last
is last element in seq
None
height
fromPole
toPole
withPole
disk
fp
tp
anchors
url
anchors
f
None
query
searchfor
alist
verbose
False
w
alist
Authors: kgashok
iterative mergesort implementation
series
is a sequence of unsorted elements
score
gradeChart
scores
gc
Generates 20 lists of random sizes within the range -5, 10, inclusive. Modify these as per your choice
Authors: kgashok
function implements qsort algorithm in recursive mode
array
is list of numbers to be sorted
L
Authors: kgashok
function implements binary search algorithm using slicing
alist
is list of numbers to be searched
token
is the number to be find in the list
Asks the player for a move. Returns (fromTower, toTower).
towers
Display the current state.
towers
Display a disk of the given width. A width of 0 means no disk.
width
Authors: kgashok
calculate the grade given a score and a grading chart.
score
individual student's score
gradeChart
list of tuples
Authors: kgashok
returns the average grade for the entire class
scores
list of student scores
gc
list of tuples
a simple example to start you off
Authors: kgashok
http://www.w3.org/TR/html5/text-level-semantics.html#the-a-element anchors contains all <a> tag elements from the HTML content. Iterate through the list of anchors and build list containing the href addresses whenever it is available.
anchors
alist
url
anchorCount
outBoundCount
linkCount
Print only those addresses that start with 'https' from valid anchors if 'f'ilename is valid, write extracted URLs to file as well
url
anchors
f
None
generate the Lucas Sequence and return upto n elements in a list and ref: https://cyber-dojo.org/kata/edit/s4Z3PL
number
Authors: kgashok
generate the Lucas sequence using another 3 element list
number
is an int
a_tags
url
anchorCount
linkCount
url
anchors
f
None
anchors
alist
Authors: kgashok
swap the contents of a and b
a
is global
b
is global
Authors: kgashok
Computes the distance between two Point objects.
pointA
is a tuple
pointB
is a tuple
Generates 20 lists of random sizes within the range - 5, 10, inclusive.Modify these as per your choice
alist
Print a Point object in human-readable format.
p
Returns a Point at the center of a Rectangle. rect: Rectangle returns: new Point
rect
Modifies the Rectangle by adding to its width and height. rect: Rectangle object. dwidth: change in width (can be negative). dheight: change in height (can be negative).
rect
dwidth
dheight
Computes factorial of n recursively.
n
Computes an estimate of pi. Algorithm due to Srinivasa Ramanujan, from http://en.wikipedia.org/wiki/Pi
Read the words in words.txt and return a dictionary that contains the words as keys
Prints all words that can be generated by rotating word. word: string word_dict: dictionary with words as keys
word
word_dict
Returns i as a string with at least n digits. i: int n: int length returns: string
i
n
Checks if i and j are the reverse of each other. i: int j: int returns:bool
i
j
Counts the number of palindromic ages. Returns the number of times the mother and daughter have palindromic ages in their lives, given the difference in age. diff: int difference in ages flag: bool, if True, prints the details
diff
flag
False
Finds age differences that satisfy the problem. Enumerates the possible differences in age between mother and daughter, and for each difference, counts the number of times over their lives they will have ages that are the reverse of each other.
Prints the names of all files in dirname and its subdirectories. This is the version in the book. dirname: string name of directory
dirname
Prints the names of all files in dirname and its subdirectories. This is the exercise solution, which uses os.walk. dirname: string name of directory
dirname
Draws a square with sides of the given length. Returns the Turtle to the starting position and location.
t
length
Draws n line segments. t: Turtle object n: number of line segments length: length of each segment angle: degrees between segments
t
n
length
angle
Draws a polygon with n sides. t: Turtle n: number of sides length: length of each side.
t
n
length
Draws an arc with the given radius and angle. t: Turtle r: radius angle: angle subtended by the arc, in degrees
t
r
angle
Draws a circle with the given radius. t: Turtle r: radius
t
r
Computes the total of all numbers in a list of lists. t: list of list of numbers returns: number
t
Computes the cumulative sum of the numbers in t. t: list of numbers returns: list of numbers
t
Returns all but the first and last elements of t. t: list returns: new list
t
Removes the first and last elements of t. t: list returns: None
t
Checks whether a list is sorted. t: list returns: boolean
t
Checks whether two words are anagrams word1: string or list word2: string or list returns: boolean
word1
word2
Returns True if any element appears more than once in a sequence. s: string or list returns: bool
s
Moves the turtle without drawing a line. Postcondition: pen is down t: Turtle x: coordinate y: coordinate
t
x
y
Handles the event when a user presses a key. Checks if there is a function with the right name; otherwise it prints an error message. char: string, letter to draw
char
Moves to the beginning of the next line.
Returns a function object that executes keypress. char: character to draw when the function is executed returns: function with no arguments
char
Finds and returns the class object that will provide the definition of method_name (as a string) if it is invoked on obj. obj: any python object method_name: string method name
obj
method_name
Computes the Ackermann function A(m, n) See http://en.wikipedia.org/wiki/Ackermann_function n, m: non-negative integers
m
n
Read. the words in words.txt and return a dictionary that contains the words as keys.
Checks if words two can be pronounced the same way. If either word is not in the pronouncing dictionary, return False a, b: strings phonetic: map from words to pronunciation codes
a
b
phonetic
Checks to see if the word has the following property: removing the first letter yields a word with the same pronunciation, and removing the second letter yields a word with the same pronunciation. word: string word_dict: dictionary with words as keys phonetic: map from words to pronunciation codes
word
word_dict
phonetic
Finds the names of all files in dirname and its subdirectories. dirname: string name of directory
dirname
Computes the MD5 checksum of the contents of a file. filename: string
filename
Computes the difference between the contents of two files. name1, name2: string filenames
name1
name2
Runs a command in a subprocess. cmd: string Unix command Returns (res, stat), the output of the subprocess and the exit status.
cmd
Computes checksums for all files with the given suffix. dirname: string name of directory to search suffix: string suffix to match Returns: map from checksum to list of files with that checksum
dirname
suffix
Checks whether any in a list of files differs from the others. names: list of string filenames
names
Checks for duplicate files. Reports any files with the same checksum and checks whether they are, in fact, identical. d: map from checksum to list of files with that checksum
d
Reads a source file and writes the destination file. In each line, replaces pattern with replace. pattern: string replace: string source: string filename dest: string filename
pattern
replace
source
dest
Rotates a letter by n places. Does not change other chars. letter: single-letter string n: int Returns: single-letter string
letter
n
Rotates a word by n places. word: string n: integer Returns: string
word
n
Runs a function twice. func: function object arg: argument passed to the function
func
arg
Prints the argument twice. arg: anything printable
arg
Runs a function four times. func: function object arg: argument passed to the function
func
arg
Stores the anagrams from a dictionary in a shelf. filename: string file name of shelf anagram_map: dictionary that maps strings to list of anagrams
filename
anagram_map
Looks up a word in a shelf and returns a list of its anagrams. filename: string file name of shelf word: word to look up
filename
word
script
command
"make_db"
Checks whether a word contains two interleaved words. word_list: list of strings word: string
word_list
word
Checks whether a word contains n interleaved words. word_list: list of strings word: string n: number of interleaved words
word_list
word
n
3
Draws a circle. t: Turtle circle: Circle
t
circle
Draws a rectangle. t: Turtle rect: Rectangle
t
rect
Prints a string representation of the time. t: Time object
t
Makes a new Time object. seconds: int seconds since midnight.
seconds
Computes the number of seconds since midnight. time: Time object.
time
Adds two time objects. t1, t2: Time returns: Time
t1
t2
Checks whether a Time object satisfies the invariants. time: Time returns: boolean
time
Draws a petal using two arcs. t: Turtle r: radius of the arcs angle: angle (degrees) that subtends the arcs
t
r
angle
Draws a flower with n petals. t: Turtle n: number of petals r: radius of the arcs angle: angle (degrees) that subtends the arcs
t
n
r
angle
Move Turtle (t) forward (length) units without leaving a trail. Leaves the pen down.
t
length
script
filename
"emma.txt"
n
100
order
2
Reads lines from a file and builds a list using append. returns: list of strings
Checks whether a word is in a list using bisection search. Precondition: the words in the list are sorted word_list: list of strings word: string
word_list
word
Checks whether a word is in a list using bisection search. Precondition: the words in the list are sorted word_list: list of strings word: string
word_list
word
Print all pairs of words that differ by swapping two letters. d: map from word to list of anagrams
d
Computes the number of differences between two words. word1, word2: strings Returns: integer
word1
word2
Reads from a file and builds a dictionary that maps from each word to a string that describes its primary pronunciation. Secondary pronunciations are added to the dictionary with a number, in parentheses, at the end of the key, so the key for the second pronunciation of "abdominal" is "abdominal(2)". filename: string returns: map from string to pronunciation
filename
"c06d"
Returns a string that describes the shape of a data structure. ds: any Python object Returns: string
ds
Returns a string representation of a list of type strings. t: list of strings Returns: string
t
Returns a string representation of a set of type strings. s: set of strings Returns: string
s
Adds a new element to a list of type strings. Modifies res. res: list of type strings typestr: the new type string count: how many of the new type there are Returns: None
res
typestr
count
Returns the signature of this string. Signature is a string that contains all of the letters in order. s: string
s
Finds all anagrams in a list of words. filename: string filename of the word list Returns: a map from each word to a list of its anagrams.
filename
Prints the anagram sets in d. d: map from words to list of their anagrams
d
Prints the anagram sets in d in decreasing order of size. d: map from words to list of their anagrams
d
Select only the words in d that have n letters. d: map from word to list of anagrams n: integer number of letters returns: new map from word to list of anagrams
d
n
Chooses a random word from a histogram. The probability of each word is proportional to its frequency. hist: map from word to frequency
hist
Computes the distance between two Point objects. p1: Point p2: Point returns: float
p1
p2
Move the Rectangle by modifying its corner object. rect: Rectangle object. dx: change in x coordinate (can be negative). dy: change in y coordinate (can be negative).
rect
dx
dy
Move the Rectangle and return a new Rectangle object. rect: Rectangle object. dx: change in x coordinate (can be negative). dy: change in y coordinate (can be negative). returns: new Rectangle
rect
dx
dy
Makes a new Time object. seconds: int seconds since midnight.
seconds
Returns True if t1 is after t2; false otherwise.
t1
t2
Adds seconds to a Time object.
t1
seconds
Multiplies a Time object by a factor.
t1
factor
How long until my next birthday?
birthday
Compute the day when one person is twice as old as the other. b1: datetime birthday of the younger person b2: datetime birthday of the older person
b1
b2
Exercise solutions.
Reads lines from a file and builds a list using append.
Reads lines from a file and builds a list using list +.
Returns a set of all keys that appear in d1 but not d2. d1, d2: dictionaries
d1
d2
test function which is used to validate if the custom packge installation worked successfully
Finds the names of all files in dirname and its subdirectories. dirname: string name of directory
dirname
Computes the MD5 checksum of the contents of a file. filename: string
filename
Computes the difference between the contents of two files. name1, name2: string filenames
name1
name2
Runs a command in a subprocess. cmd: string Unix command Returns (res, stat), the output of the subprocess and the exit status.
cmd
Computes checksums for all files with the given suffix. dirname: string name of directory to search suffix: string suffix to match Returns: map from checksum to list of files with that checksum
dirname
suffix
Checks whether any in a list of files differs from the others. names: list of string filenames
names
Checks for duplicate files. Reports any files with the same checksum and checks whether they are, in fact, identical. d: map from checksum to list of files with that checksum
d
Makes a histogram that contains the words from a file. filename: string skip_header: boolean, whether to skip the Gutenberg header returns: map from each word to the number of times it appears.
filename
skip_header
Reads from fp until it finds the line that ends the header. fp: open file object
fp
Adds the words in the line to the histogram. Modifies hist. line: string hist: histogram (map from word to frequency)
line
hist
Makes a list of word-freq pairs in descending order of frequency. hist: map from word to frequency returns: list of (frequency, word) pairs
hist
Prints the most commons words in a histgram and their frequencies. hist: histogram (map from word to frequency) num: number of words to print
hist
num
10
Returns a dictionary with all keys that appear in d1 but not d2. d1, d2: dictionaries
d1
d2
Returns the total of the frequencies in a histogram.
hist
Returns the number of different words in a histogram.
hist
Chooses a random word from a histogram. The probability of each word is proportional to its frequency.
hist
Returns the first character of a string.
word
Returns the last of a string.
word
Returns all but the first and last characters of a string.
word
Returns True if word is a palindrome.
word
Reads a word list and returns a dictionary.
If word is reducible, returns a list of its reducible children. Also adds an entry to the memo dictionary. A string is reducible if it has at least one child that is reducible. The empty string is also reducible. word: string word_dict: dictionary with words as keys
word
word_dict
Returns a list of all words that can be formed by removing one letter. word: string Returns: list of strings
word
word_dict
Checks all words in the word_dict; returns a list reducible ones. word_dict: dictionary with words as keys
word_dict
Prints the sequence of words that reduces this word to the empty string. If there is more than one choice, it chooses the first. word: string
word
Finds the longest reducible words and prints them. word_dict: dictionary of valid words
word_dict
f
f
f
g
h
do nothing
Returns True if any element appears more than once in a sequence. t: list returns: bool
t
Returns a list of integers between 1 and 365, with length n. n: int returns: list of int
n
Generates a sample of birthdays and counts duplicates. num_students: how many students in the group num_samples: how many groups to simulate returns: int
num_students
num_simulations
Runs the birthday simulation and prints the number of matches.
Tests if a word contains three consecutive double letters. word: string returns: bool
word
Reads a word list and prints words with triple double letters.
Checks whether a point lies inside a circle (or on the boundary). point: Point object circle: Circle object
point
circle
Checks whether the corners of a rect fall in/on a circle. rect: Rectangle object circle: Circle object
rect
circle
Checks whether any corners of a rect fall in/on a circle. rect: Rectangle object circle: Circle object
rect
circle
Draws an Archimedian spiral starting at the origin. Args: n: how many line segments to draw length: how long each segment is a: how loose the initial spiral starts out (larger is looser) b: how loosly coiled the spiral is (larger is looser) http://en.wikipedia.org/wiki/Spiral
t
n
length
3
a
0.1
b
0.0002
Sorts the letters in s in reverse order of frequency. s: string Returns: list of letters
s
Make a map from letters to number of times they appear in s. s: string Returns: map from letter to frequency
s
Returns the contents of a file as a string.
filename
Returns a list of (rank, freq) tuples. hist: map from word to frequency returns: list of (rank, freq) tuples
hist
Prints the rank vs. frequency data. hist: map from word to frequency
hist
Plots frequency vs. rank. hist: map from word to frequency scale: string 'linear' or 'log'
hist
scale
"log"
script
filename
"emma.txt"
flag
"plot"
Runs a command in a subprocess. cmd: string Unix command Returns (res, stat), the output of the subprocess and the exit status.
cmd
Checks whether a reversed word appears in word_list. word_list: list of strings word: string
word_list
word
t
length
t
length
t
angle
90
t
angle
90
t
t
forward and left
t
n
angle
90
forward and back, ending at the original position
t
n
lift the pen and move
t
n
Makes a vertical line and leave the turtle at the top, facing right
t
n
angle
90
move the turtle vertically and leave it at the top, facing right
t
n
Makes a vertical line and return to the original position
t
n
Makes a horizontal line at the given height and return.
t
n
height
Makes a vertical line to the given height and a horizontal line at the given height and then return. This is efficient to implement, and turns out to be useful, but it's not so semantically clean.
t
n
height
Makes a diagonal line to the given x, y offsets and return
t
x
y
t
n
height
Makes a bump with radius n at height*n
t
n
height
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
t
n
Draws a pie, then moves into position to the right. t: Turtle n: number of segments r: length of the radial spokes
t
n
r
Draws a pie divided into radial segments. t: Turtle n: number of segments r: length of the radial spokes
t
n
r
Draws an icosceles triangle. The turtle starts and ends at the peak, facing the middle of the base. t: Turtle r: length of the equal legs angle: peak angle in degrees
t
r
angle
script
filename
"emma.txt"
n
100
order
2
Inverts a dictionary, returning a map from val to a list of keys. If the mapping key->val appears in d, then in the new dictionary val maps to a list that includes key. d: dict Returns: dict
d
Computes the Ackermann function A(m, n) See http://en.wikipedia.org/wiki/Ackermann_function n, m: non-negative integers
m
n
Makes a new Time object. seconds: int seconds since midnight.
seconds
Sort a list of words in reverse order by length. This is the version in the book; it is stable in the sense that words with the same length appear in the same order words: list of strings Returns: list of strings
words
Sort a list of words in reverse order by length. This is the solution to the exercise. It is unstable in the sense that if two words have the same length, their order in the output list is random. It works by extending the list of tuples with a column of random numbers; when there is a tie in the first column, the random column determines the output order. words: list of strings Returns: list of strings
words
Checks whether any element appears more than once in a sequence. Simple version using a for loop. t: sequence
t
Checks whether any element appears more than once in a sequence. Faster version using a set. t: sequence
t
Draws a koch curve with length n.
t
n
Draws a snowflake (a triangle with a Koch curve for each side).
t
n
Checks if the string representation of i has a palindrome. i: integer start: where in the string to start length: length of the palindrome to check for
i
start
length
Checks if the integer (i) has the desired properties. i: int
i
Enumerate the six-digit numbers and print any winners.
test function which is used to validate if the custom packge installation worked successfully
: An implementation of a hashtable using a BetterMap that grows so that the number of items never exceeds the number of LinearMaps. The amortized cost of add should be O(1) provided that the implementation of sum in resize is linear.
: Represents a circle. Attributes: center, radius
: A Kangaroo is a marsupial.
: A map from each item (x) to its frequency.
: Represents a poker hand.
: Represents a deck of cards that can deal poker hands.
: Encapsulates the statistical summary of a text.
: Represents the time of day. attributes: hour, minute, second
: A Kangaroo is a marsupial.