Python Documentation

Classes

State: enum class to represent possible cell states

Board: Board class to represent the game board

Point: Represents a point in 2-D space. attributes: x, y

Rectangle: Represents a rectangle. attributes: width, height, corner.

Card: Represents a standard playing card. Attributes: suit: integer 0-3 rank: integer 1-13

Deck: Represents a deck of cards. Attributes: cards: list of Card objects.

Hand: Represents a hand of playing cards.

Time: Represents the time of day. attributes: hour, minute, second

Markov: Encapsulates the statistical summary of a text.

Point: Represents a point in 2-D space. attributes: x, y

Test:

Time: Represents the time of day. attributes: hour, minute, second

PokerHand: Represents a poker hand.

LinearMap: A simple implementation of a map using a list of tuples where each tuple is a key-value pair.

BetterMap: 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.

HashMap: 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.

Circle: Represents a circle. Attributes: center, radius

Kangaroo: A Kangaroo is a marsupial.

Hist: A map from each item (x) to its frequency.

PokerHand: Represents a poker hand.

PokerDeck: Represents a deck of cards that can deal poker hands.

Markov: Encapsulates the statistical summary of a text.

Time: Represents the time of day. attributes: hour, minute, second

Kangaroo: A Kangaroo is a marsupial.

Functions

fprint

My own function source code inspection function Filters out any print statements and input statements

Parameters

namedescriptiondefault

fname

divideTwo

function which takes a list and returns two halves

Parameters

namedescriptiondefault

al

merge

merge generates a new sorted list containing all elements contained in both sorted lists

Parameters

namedescriptiondefault

A

B

mergesort

sorts the list using the mergesort algorithm

Parameters

namedescriptiondefault

alist

fprint

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

Parameters

namedescriptiondefault

fname

selection_sort

Pure implementation of the selection sort algorithm in Python

Parameters

namedescriptiondefault

collection:

some mutable ordered collection with heterogeneous comparable items inside

collection

swap

swap two elements in a list

Parameters

namedescriptiondefault

alist

ai

bi

min_index

Parameters

namedescriptiondefault

alist

i

Parameters

namedescriptiondefault

hlist

selectsort

Parameters

namedescriptiondefault

alist

selectsortf

Parameters

namedescriptiondefault

alist

selectsortc

Parameters

namedescriptiondefault

alist

selectsortd

Parameters

namedescriptiondefault

alist

min_index_c

function returns the index of the minimum value in the sublist alist[i:]

Parameters

namedescriptiondefault

alist

i

circulate

Authors: kgashok

circulate between three variables, three times

Parameters

namedescriptiondefault

a

is a integer

b

is a integer

c

is a integer

circulate_list

Authors: kgashok

circulate 'n' elements in a list, n times

Parameters

namedescriptiondefault

alist

contains the 'n' elements

is_palindrome

Authors: kgashok

check whether a sequence is palindromic using unpacking

Parameters

namedescriptiondefault

aseq

is a sequence, for e.g. string or list

is_palindrome_rec

Authors: kgashok

check for palindrome using unpacking, recursively

Parameters

namedescriptiondefault

aseq

is a sequence of elements, string or list

is_palindrome_rec_slice

Authors: kgashok

check for palindrome using slicing, recursively

Parameters

namedescriptiondefault

aseq

is a sequence of elements, string or list

first

is first element in seq

None

last

is last element in seq

None

moveTower

Parameters

namedescriptiondefault

height

fromPole

toPole

withPole

moveDisk

Parameters

namedescriptiondefault

disk

fp

tp

get_addresses

Parameters

namedescriptiondefault

anchors

printURLs

Parameters

namedescriptiondefault

url

anchors

f

None

googleSearch

Parameters

namedescriptiondefault

query

googlesearch

Parameters

namedescriptiondefault

searchfor

mergesort

Parameters

namedescriptiondefault

alist

verbose

False

mergesort2

Parameters

namedescriptiondefault

w

printlist

Parameters

namedescriptiondefault

alist

mergesort

Authors: kgashok

iterative mergesort implementation

Parameters

namedescriptiondefault

series

is a sequence of unsorted elements

calculateGrade

Parameters

namedescriptiondefault

score

gradeChart

classAverage

Parameters

namedescriptiondefault

scores

gc

test_random_lists

Generates 20 lists of random sizes within the range -5, 10, inclusive. Modify these as per your choice

qsort_one_liner

Authors: kgashok

function implements qsort algorithm in recursive mode

Parameters

namedescriptiondefault

array

is list of numbers to be sorted

qsort

Parameters

namedescriptiondefault

L

Authors: kgashok

function implements binary search algorithm using slicing

Parameters

namedescriptiondefault

alist

is list of numbers to be searched

token

is the number to be find in the list

main

askForPlayerMove

Asks the player for a move. Returns (fromTower, toTower).

Parameters

namedescriptiondefault

towers

displayTowers

Display the current state.

Parameters

namedescriptiondefault

towers

displayDisk

Display a disk of the given width. A width of 0 means no disk.

Parameters

namedescriptiondefault

width

calculate_grade

Authors: kgashok

calculate the grade given a score and a grading chart.

Parameters

namedescriptiondefault

score

individual student's score

gradeChart

list of tuples

class_average

Authors: kgashok

returns the average grade for the entire class

Parameters

namedescriptiondefault

scores

list of student scores

gc

list of tuples

test_life_the_universe_and_everything

a simple example to start you off

getOutBoundURLs

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.

Parameters

namedescriptiondefault

anchors

getOutBoundHttpURLs

Parameters

namedescriptiondefault

alist

generateBanner

Parameters

namedescriptiondefault

url

anchorCount

outBoundCount

linkCount

printURLs

Print only those addresses that start with 'https' from valid anchors if 'f'ilename is valid, write extracted URLs to file as well

Parameters

namedescriptiondefault

url

anchors

f

None

sequence_gen

generate the Lucas Sequence and return upto n elements in a list and ref: https://cyber-dojo.org/kata/edit/s4Z3PL

Parameters

namedescriptiondefault

number

sequence_gen_alt

Authors: kgashok

generate the Lucas sequence using another 3 element list

Parameters

namedescriptiondefault

number

is an int

test_for_three_elements

test_for_five_elements

test_for_big_numbers

getOutBoundURLs

Parameters

namedescriptiondefault

a_tags

generateBanner

Parameters

namedescriptiondefault

url

anchorCount

linkCount

printURLs

Parameters

namedescriptiondefault

url

anchors

f

None

getOutBoundURLs2

Parameters

namedescriptiondefault

anchors

getOutBoundHttpURLs

Parameters

namedescriptiondefault

alist

swap_func

Authors: kgashok

swap the contents of a and b

Parameters

namedescriptiondefault

a

is global

b

is global

distance_between

Authors: kgashok

Computes the distance between two Point objects.

Parameters

namedescriptiondefault

pointA

is a tuple

pointB

is a tuple

test_random_lists

Generates 20 lists of random sizes within the range - 5, 10, inclusive.Modify these as per your choice

missing_plane

Parameters

namedescriptiondefault

alist

Print a Point object in human-readable format.

Parameters

namedescriptiondefault

p

find_center

Returns a Point at the center of a Rectangle. rect: Rectangle returns: new Point

Parameters

namedescriptiondefault

rect

grow_rectangle

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).

Parameters

namedescriptiondefault

rect

dwidth

dheight

main

factorial

Computes factorial of n recursively.

Parameters

namedescriptiondefault

n

estimate_pi

Computes an estimate of pi. Algorithm due to Srinivasa Ramanujan, from http://en.wikipedia.org/wiki/Pi

make_word_dict

Read the words in words.txt and return a dictionary that contains the words as keys

rotate_pairs

Prints all words that can be generated by rotating word. word: string word_dict: dictionary with words as keys

Parameters

namedescriptiondefault

word

word_dict

str_fill

Returns i as a string with at least n digits. i: int n: int length returns: string

Parameters

namedescriptiondefault

i

n

are_reversed

Checks if i and j are the reverse of each other. i: int j: int returns:bool

Parameters

namedescriptiondefault

i

j

num_instances

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

Parameters

namedescriptiondefault

diff

flag

False

check_diffs

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.

walk

Prints the names of all files in dirname and its subdirectories. This is the version in the book. dirname: string name of directory

Parameters

namedescriptiondefault

dirname

walk2

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

Parameters

namedescriptiondefault

dirname

square

Draws a square with sides of the given length. Returns the Turtle to the starting position and location.

Parameters

namedescriptiondefault

t

length

polyline

Draws n line segments. t: Turtle object n: number of line segments length: length of each segment angle: degrees between segments

Parameters

namedescriptiondefault

t

n

length

angle

polygon

Draws a polygon with n sides. t: Turtle n: number of sides length: length of each side.

Parameters

namedescriptiondefault

t

n

length

arc

Draws an arc with the given radius and angle. t: Turtle r: radius angle: angle subtended by the arc, in degrees

Parameters

namedescriptiondefault

t

r

angle

circle

Draws a circle with the given radius. t: Turtle r: radius

Parameters

namedescriptiondefault

t

r

nested_sum

Computes the total of all numbers in a list of lists. t: list of list of numbers returns: number

Parameters

namedescriptiondefault

t

cumsum

Computes the cumulative sum of the numbers in t. t: list of numbers returns: list of numbers

Parameters

namedescriptiondefault

t

middle

Returns all but the first and last elements of t. t: list returns: new list

Parameters

namedescriptiondefault

t

chop

Removes the first and last elements of t. t: list returns: None

Parameters

namedescriptiondefault

t

is_sorted

Checks whether a list is sorted. t: list returns: boolean

Parameters

namedescriptiondefault

t

is_anagram

Checks whether two words are anagrams word1: string or list word2: string or list returns: boolean

Parameters

namedescriptiondefault

word1

word2

has_duplicates

Returns True if any element appears more than once in a sequence. s: string or list returns: bool

Parameters

namedescriptiondefault

s

main

teleport

Moves the turtle without drawing a line. Postcondition: pen is down t: Turtle x: coordinate y: coordinate

Parameters

namedescriptiondefault

t

x

y

keypress

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

Parameters

namedescriptiondefault

char

carriage_return

Moves to the beginning of the next line.

presser

Returns a function object that executes keypress. char: character to draw when the function is executed returns: function with no arguments

Parameters

namedescriptiondefault

char

find_defining_class

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

Parameters

namedescriptiondefault

obj

method_name

ackermann

Computes the Ackermann function A(m, n) See http://en.wikipedia.org/wiki/Ackermann_function n, m: non-negative integers

Parameters

namedescriptiondefault

m

n

make_word_dict

Read. the words in words.txt and return a dictionary that contains the words as keys.

homophones

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

Parameters

namedescriptiondefault

a

b

phonetic

check_word

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

Parameters

namedescriptiondefault

word

word_dict

phonetic

walk

Finds the names of all files in dirname and its subdirectories. dirname: string name of directory

Parameters

namedescriptiondefault

dirname

compute_checksum

Computes the MD5 checksum of the contents of a file. filename: string

Parameters

namedescriptiondefault

filename

check_diff

Computes the difference between the contents of two files. name1, name2: string filenames

Parameters

namedescriptiondefault

name1

name2

pipe

Runs a command in a subprocess. cmd: string Unix command Returns (res, stat), the output of the subprocess and the exit status.

Parameters

namedescriptiondefault

cmd

compute_checksums

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

Parameters

namedescriptiondefault

dirname

suffix

check_pairs

Checks whether any in a list of files differs from the others. names: list of string filenames

Parameters

namedescriptiondefault

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

Parameters

namedescriptiondefault

d

sed

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

Parameters

namedescriptiondefault

pattern

replace

source

dest

main

rotate_letter

Rotates a letter by n places. Does not change other chars. letter: single-letter string n: int Returns: single-letter string

Parameters

namedescriptiondefault

letter

n

rotate_word

Rotates a word by n places. word: string n: integer Returns: string

Parameters

namedescriptiondefault

word

n

do_twice

Runs a function twice. func: function object arg: argument passed to the function

Parameters

namedescriptiondefault

func

arg

Prints the argument twice. arg: anything printable

Parameters

namedescriptiondefault

arg

do_four

Runs a function four times. func: function object arg: argument passed to the function

Parameters

namedescriptiondefault

func

arg

store_anagrams

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

Parameters

namedescriptiondefault

filename

anagram_map

read_anagrams

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

Parameters

namedescriptiondefault

filename

word

main

Parameters

namedescriptiondefault

script

command

"make_db"

interlock

Checks whether a word contains two interleaved words. word_list: list of strings word: string

Parameters

namedescriptiondefault

word_list

word

interlock_general

Checks whether a word contains n interleaved words. word_list: list of strings word: string n: number of interleaved words

Parameters

namedescriptiondefault

word_list

word

n

3

draw_circle

Draws a circle. t: Turtle circle: Circle

Parameters

namedescriptiondefault

t

circle

draw_rect

Draws a rectangle. t: Turtle rect: Rectangle

Parameters

namedescriptiondefault

t

rect

Prints a string representation of the time. t: Time object

Parameters

namedescriptiondefault

t

int_to_time

Makes a new Time object. seconds: int seconds since midnight.

Parameters

namedescriptiondefault

seconds

time_to_int

Computes the number of seconds since midnight. time: Time object.

Parameters

namedescriptiondefault

time

add_times

Adds two time objects. t1, t2: Time returns: Time

Parameters

namedescriptiondefault

t1

t2

valid_time

Checks whether a Time object satisfies the invariants. time: Time returns: boolean

Parameters

namedescriptiondefault

time

main

petal

Draws a petal using two arcs. t: Turtle r: radius of the arcs angle: angle (degrees) that subtends the arcs

Parameters

namedescriptiondefault

t

r

angle

flower

Draws a flower with n petals. t: Turtle n: number of petals r: radius of the arcs angle: angle (degrees) that subtends the arcs

Parameters

namedescriptiondefault

t

n

r

angle

move

Move Turtle (t) forward (length) units without leaving a trail. Leaves the pen down.

Parameters

namedescriptiondefault

t

length

main

Parameters

namedescriptiondefault

script

filename

"emma.txt"

n

100

order

2

make_word_list

Reads lines from a file and builds a list using append. returns: list of strings

in_bisect

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

Parameters

namedescriptiondefault

word_list

word

in_bisect_cheat

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

Parameters

namedescriptiondefault

word_list

word

metathesis_pairs

Print all pairs of words that differ by swapping two letters. d: map from word to list of anagrams

Parameters

namedescriptiondefault

d

word_distance

Computes the number of differences between two words. word1, word2: strings Returns: integer

Parameters

namedescriptiondefault

word1

word2

read_dictionary

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

Parameters

namedescriptiondefault

filename

"c06d"

structshape

Returns a string that describes the shape of a data structure. ds: any Python object Returns: string

Parameters

namedescriptiondefault

ds

listrep

Returns a string representation of a list of type strings. t: list of strings Returns: string

Parameters

namedescriptiondefault

t

setrep

Returns a string representation of a set of type strings. s: set of strings Returns: string

Parameters

namedescriptiondefault

s

append

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

Parameters

namedescriptiondefault

res

typestr

count

main

signature

Returns the signature of this string. Signature is a string that contains all of the letters in order. s: string

Parameters

namedescriptiondefault

s

all_anagrams

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.

Parameters

namedescriptiondefault

filename

Prints the anagram sets in d. d: map from words to list of their anagrams

Parameters

namedescriptiondefault

d

Prints the anagram sets in d in decreasing order of size. d: map from words to list of their anagrams

Parameters

namedescriptiondefault

d

filter_length

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

Parameters

namedescriptiondefault

d

n

random_word

Chooses a random word from a histogram. The probability of each word is proportional to its frequency. hist: map from word to frequency

Parameters

namedescriptiondefault

hist

main

distance_between_points

Computes the distance between two Point objects. p1: Point p2: Point returns: float

Parameters

namedescriptiondefault

p1

p2

move_rectangle

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).

Parameters

namedescriptiondefault

rect

dx

dy

move_rectangle_copy

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

Parameters

namedescriptiondefault

rect

dx

dy

main

int_to_time

Makes a new Time object. seconds: int seconds since midnight.

Parameters

namedescriptiondefault

seconds

main

is_after

Returns True if t1 is after t2; false otherwise.

Parameters

namedescriptiondefault

t1

t2

increment

Adds seconds to a Time object.

Parameters

namedescriptiondefault

t1

seconds

mul_time

Multiplies a Time object by a factor.

Parameters

namedescriptiondefault

t1

factor

days_until_birthday

How long until my next birthday?

Parameters

namedescriptiondefault

birthday

double_day

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

Parameters

namedescriptiondefault

b1

b2

datetime_exercises

Exercise solutions.

main

make_word_list1

Reads lines from a file and builds a list using append.

make_word_list2

Reads lines from a file and builds a list using list +.

subtract

Returns a set of all keys that appear in d1 but not d2. d1, d2: dictionaries

Parameters

namedescriptiondefault

d1

d2

main

test_fun

test function which is used to validate if the custom packge installation worked successfully

walk

Finds the names of all files in dirname and its subdirectories. dirname: string name of directory

Parameters

namedescriptiondefault

dirname

compute_checksum

Computes the MD5 checksum of the contents of a file. filename: string

Parameters

namedescriptiondefault

filename

check_diff

Computes the difference between the contents of two files. name1, name2: string filenames

Parameters

namedescriptiondefault

name1

name2

pipe

Runs a command in a subprocess. cmd: string Unix command Returns (res, stat), the output of the subprocess and the exit status.

Parameters

namedescriptiondefault

cmd

compute_checksums

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

Parameters

namedescriptiondefault

dirname

suffix

check_pairs

Checks whether any in a list of files differs from the others. names: list of string filenames

Parameters

namedescriptiondefault

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

Parameters

namedescriptiondefault

d

process_file

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.

Parameters

namedescriptiondefault

filename

skip_header

skip_gutenberg_header

Reads from fp until it finds the line that ends the header. fp: open file object

Parameters

namedescriptiondefault

fp

process_line

Adds the words in the line to the histogram. Modifies hist. line: string hist: histogram (map from word to frequency)

Parameters

namedescriptiondefault

line

hist

most_common

Makes a list of word-freq pairs in descending order of frequency. hist: map from word to frequency returns: list of (frequency, word) pairs

Parameters

namedescriptiondefault

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

Parameters

namedescriptiondefault

hist

num

10

subtract

Returns a dictionary with all keys that appear in d1 but not d2. d1, d2: dictionaries

Parameters

namedescriptiondefault

d1

d2

total_words

Returns the total of the frequencies in a histogram.

Parameters

namedescriptiondefault

hist

different_words

Returns the number of different words in a histogram.

Parameters

namedescriptiondefault

hist

random_word

Chooses a random word from a histogram. The probability of each word is proportional to its frequency.

Parameters

namedescriptiondefault

hist

main

first

Returns the first character of a string.

Parameters

namedescriptiondefault

word

last

Returns the last of a string.

Parameters

namedescriptiondefault

word

middle

Returns all but the first and last characters of a string.

Parameters

namedescriptiondefault

word

is_palindrome

Returns True if word is a palindrome.

Parameters

namedescriptiondefault

word

make_word_dict

Reads a word list and returns a dictionary.

is_reducible

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

Parameters

namedescriptiondefault

word

word_dict

children

Returns a list of all words that can be formed by removing one letter. word: string Returns: list of strings

Parameters

namedescriptiondefault

word

word_dict

all_reducible

Checks all words in the word_dict; returns a list reducible ones. word_dict: dictionary with words as keys

Parameters

namedescriptiondefault

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

Parameters

namedescriptiondefault

word

Finds the longest reducible words and prints them. word_dict: dictionary of valid words

Parameters

namedescriptiondefault

word_dict

do_twice

Parameters

namedescriptiondefault

f

do_four

Parameters

namedescriptiondefault

f

print_post

one_four_one

Parameters

namedescriptiondefault

f

g

h

nothing

do nothing

print1beam

print1post

print4beams

print4posts

has_duplicates

Returns True if any element appears more than once in a sequence. t: list returns: bool

Parameters

namedescriptiondefault

t

random_bdays

Returns a list of integers between 1 and 365, with length n. n: int returns: list of int

Parameters

namedescriptiondefault

n

count_matches

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

Parameters

namedescriptiondefault

num_students

num_simulations

main

Runs the birthday simulation and prints the number of matches.

main

is_triple_double

Tests if a word contains three consecutive double letters. word: string returns: bool

Parameters

namedescriptiondefault

word

find_triple_double

Reads a word list and prints words with triple double letters.

point_in_circle

Checks whether a point lies inside a circle (or on the boundary). point: Point object circle: Circle object

Parameters

namedescriptiondefault

point

circle

rect_in_circle

Checks whether the corners of a rect fall in/on a circle. rect: Rectangle object circle: Circle object

Parameters

namedescriptiondefault

rect

circle

rect_circle_overlap

Checks whether any corners of a rect fall in/on a circle. rect: Rectangle object circle: Circle object

Parameters

namedescriptiondefault

rect

circle

main

draw_spiral

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

Parameters

namedescriptiondefault

t

n

length

3

a

0.1

b

0.0002

most_frequent

Sorts the letters in s in reverse order of frequency. s: string Returns: list of letters

Parameters

namedescriptiondefault

s

make_histogram

Make a map from letters to number of times they appear in s. s: string Returns: map from letter to frequency

Parameters

namedescriptiondefault

s

read_file

Returns the contents of a file as a string.

Parameters

namedescriptiondefault

filename

rank_freq

Returns a list of (rank, freq) tuples. hist: map from word to frequency returns: list of (rank, freq) tuples

Parameters

namedescriptiondefault

hist

Prints the rank vs. frequency data. hist: map from word to frequency

Parameters

namedescriptiondefault

hist

plot_ranks

Plots frequency vs. rank. hist: map from word to frequency scale: string 'linear' or 'log'

Parameters

namedescriptiondefault

hist

scale

"log"

main

Parameters

namedescriptiondefault

script

filename

"emma.txt"

flag

"plot"

pipe

Runs a command in a subprocess. cmd: string Unix command Returns (res, stat), the output of the subprocess and the exit status.

Parameters

namedescriptiondefault

cmd

reverse_pair

Checks whether a reversed word appears in word_list. word_list: list of strings word: string

Parameters

namedescriptiondefault

word_list

word

fd

Parameters

namedescriptiondefault

t

length

bk

Parameters

namedescriptiondefault

t

length

lt

Parameters

namedescriptiondefault

t

angle

90

rt

Parameters

namedescriptiondefault

t

angle

90

pd

Parameters

namedescriptiondefault

t

pu

Parameters

namedescriptiondefault

t

fdlt

forward and left

Parameters

namedescriptiondefault

t

n

angle

90

fdbk

forward and back, ending at the original position

Parameters

namedescriptiondefault

t

n

skip

lift the pen and move

Parameters

namedescriptiondefault

t

n

stump

Makes a vertical line and leave the turtle at the top, facing right

Parameters

namedescriptiondefault

t

n

angle

90

hollow

move the turtle vertically and leave it at the top, facing right

Parameters

namedescriptiondefault

t

n

post

Makes a vertical line and return to the original position

Parameters

namedescriptiondefault

t

n

beam

Makes a horizontal line at the given height and return.

Parameters

namedescriptiondefault

t

n

height

hangman

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.

Parameters

namedescriptiondefault

t

n

height

diagonal

Makes a diagonal line to the given x, y offsets and return

Parameters

namedescriptiondefault

t

x

y

vshape

Parameters

namedescriptiondefault

t

n

height

bump

Makes a bump with radius n at height*n

Parameters

namedescriptiondefault

t

n

height

draw_a

Parameters

namedescriptiondefault

t

n

draw_b

Parameters

namedescriptiondefault

t

n

draw_c

Parameters

namedescriptiondefault

t

n

draw_d

Parameters

namedescriptiondefault

t

n

draw_ef

Parameters

namedescriptiondefault

t

n

draw_e

Parameters

namedescriptiondefault

t

n

draw_f

Parameters

namedescriptiondefault

t

n

draw_g

Parameters

namedescriptiondefault

t

n

draw_h

Parameters

namedescriptiondefault

t

n

draw_i

Parameters

namedescriptiondefault

t

n

draw_j

Parameters

namedescriptiondefault

t

n

draw_k

Parameters

namedescriptiondefault

t

n

draw_l

Parameters

namedescriptiondefault

t

n

draw_n

Parameters

namedescriptiondefault

t

n

draw_m

Parameters

namedescriptiondefault

t

n

draw_o

Parameters

namedescriptiondefault

t

n

draw_p

Parameters

namedescriptiondefault

t

n

draw_q

Parameters

namedescriptiondefault

t

n

draw_r

Parameters

namedescriptiondefault

t

n

draw_s

Parameters

namedescriptiondefault

t

n

draw_t

Parameters

namedescriptiondefault

t

n

draw_u

Parameters

namedescriptiondefault

t

n

draw_v

Parameters

namedescriptiondefault

t

n

draw_w

Parameters

namedescriptiondefault

t

n

draw_x

Parameters

namedescriptiondefault

t

n

draw_v

Parameters

namedescriptiondefault

t

n

draw_y

Parameters

namedescriptiondefault

t

n

draw_z

Parameters

namedescriptiondefault

t

n

draw_

Parameters

namedescriptiondefault

t

n

main

draw_pie

Draws a pie, then moves into position to the right. t: Turtle n: number of segments r: length of the radial spokes

Parameters

namedescriptiondefault

t

n

r

polypie

Draws a pie divided into radial segments. t: Turtle n: number of segments r: length of the radial spokes

Parameters

namedescriptiondefault

t

n

r

isosceles

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

Parameters

namedescriptiondefault

t

r

angle

main

Parameters

namedescriptiondefault

script

filename

"emma.txt"

n

100

order

2

invert_dict

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

Parameters

namedescriptiondefault

d

ackermann

Computes the Ackermann function A(m, n) See http://en.wikipedia.org/wiki/Ackermann_function n, m: non-negative integers

Parameters

namedescriptiondefault

m

n

main

int_to_time

Makes a new Time object. seconds: int seconds since midnight.

Parameters

namedescriptiondefault

seconds

main

sort_by_length

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

Parameters

namedescriptiondefault

words

sort_by_length_random

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

Parameters

namedescriptiondefault

words

has_duplicates

Checks whether any element appears more than once in a sequence. Simple version using a for loop. t: sequence

Parameters

namedescriptiondefault

t

has_duplicates2

Checks whether any element appears more than once in a sequence. Faster version using a set. t: sequence

Parameters

namedescriptiondefault

t

koch

Draws a koch curve with length n.

Parameters

namedescriptiondefault

t

n

snowflake

Draws a snowflake (a triangle with a Koch curve for each side).

Parameters

namedescriptiondefault

t

n

has_palindrome

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

Parameters

namedescriptiondefault

i

start

length

check

Checks if the integer (i) has the desired properties. i: int

Parameters

namedescriptiondefault

i

check_all

Enumerate the six-digit numbers and print any winners.

test_fun2

test function which is used to validate if the custom packge installation worked successfully

Last updated