Docsity

Section Handout: All Things Scheme - Programming Paradigms - 33, Exercises of Programming Paradigms

Toggle sidebar
bg1
CS107 Handout 33
Spring 2008 May 19, 2008
Section Handout: All Things Scheme
Problem 1: Building Subsets of a Certain Size
Implement the k-subsets function, which accepts a set and a non-negative integer k and
constructs a list of all those subsets of the incoming set whose size just happens to equal k.
Your implementation should run in time that’s proportional to the number of subsets in the
final answer. In particular, you should not reuse the power-set implementation from lecture
and then filter on length, because that’s entirely too time-consuming when large sets are
paired with small values of k.
;; Function: k-subsets
;; -------------------
;; k-subsets constructs a list of all those subsets
;; of the specified set whose size just happens to equal k.
;;
;; Examples: (k-subsets '(1 2 3 4) 2) -> ((1 2) (1 3) (1 4) (2 3) (2 4) (3 4))
;; (k-subsets '(1 2 3 4 5 6) 1) -> ((1) (2) (3) (4) (5) (6))
;; (k-subsets '(a b c d) 0) -> (())
;; (k-subsets '(a b d d) 5) -> ()
(define (k-subsets set k)
(
Problem 2: Up Down Permutations
a. An up-down list is a homogeneous list which alternates between local minima and local
maxima—that is, the second element is larger than the first and third, the third element is
smaller than the second and fourth, the fourth element is larger than the third and fifth,
and so on. Informally, the list zig-zags up and down as you march over all of its elements.
Using car-cdr recursion, implement the is-up-down routine, which returns #t if and only if
the specified list of atoms is an up-down list according to the specified predicate. List of
length 0 and 1 are automatically considered to be up-down lists.
;; Function: is-up-down?
;; ---------------------
;; Returns true if and only if the specified list is an up-down list
;; according to the specified predicate.
;;
;; Examples: (is-up-down? '() <) -> #t
;; (is-up-down? '(1) <) -> #t
;; (is-up-down? '(1 2 2 3) <) -> #f
;; (is-up-down? '(1 6 2 4 3 5) <) -> #f
;; (is-up-down? '(1 6 2 4 3 5) >) -> #f ;; down-up, but not up-down
;; (is-up-down? '(4 8 3 5 1 7 6 2) <) -> #f
(define (is-up-down? list comp)
(
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Section Handout: All Things Scheme - Programming Paradigms - 33 and more Exercises Programming Paradigms in PDF only on Docsity!

CS107 Handout 33 Spring 2008 May 19, 2008

Section Handout: All Things Scheme

Problem 1: Building Subsets of a Certain Size

Implement the k-subsets function, which accepts a set and a non-negative integer k and

constructs a list of all those subsets of the incoming set whose size just happens to equal k.

Your implementation should run in time that’s proportional to the number of subsets in the

final answer. In particular, you should not reuse the power-set implementation from lecture

and then filter on length, because that’s entirely too time-consuming when large sets are

paired with small values of k.

;; Function: k-subsets ;; ------------------- ;; k-subsets constructs a list of all those subsets ;; of the specified set whose size just happens to equal k. ;; ;; Examples: (k-subsets '(1 2 3 4) 2) - > ((1 2) (1 3) (1 4) (2 3) (2 4) (3 4)) ;; (k-subsets '(1 2 3 4 5 6) 1) - > ((1) (2) (3) (4) (5) (6)) ;; (k-subsets '(a b c d) 0) - > (()) ;; (k-subsets '(a b d d) 5) - > () (define (k-subsets set k) (

Problem 2: Up Down Permutations

a. An up-down list is a homogeneous list which alternates between local minima and local

maxima—that is, the second element is larger than the first and third, the third element is

smaller than the second and fourth, the fourth element is larger than the third and fifth,

and so on. Informally, the list zig-zags up and down as you march over all of its elements.

Using car-cdr recursion, implement the is-up-down routine, which returns #t if and only if

the specified list of atoms is an up-down list according to the specified predicate. List of

length 0 and 1 are automatically considered to be up-down lists.

;; Function: is-up-down? ;; --------------------- ;; Returns true if and only if the specified list is an up-down list ;; according to the specified predicate. ;; ;; Examples: (is-up-down? '() <) - > #t ;; (is-up-down? '(1) <) - > #t ;; (is-up-down? '(1 2 2 3) <) - > #f ;; (is-up-down? '(1 6 2 4 3 5) <) - > #f ;; (is-up-down? '(1 6 2 4 3 5) >) - > #f ;; down-up, but not up-down ;; (is-up-down? '(4 8 3 5 1 7 6 2) <) - > #f (define (is-up-down? list comp) (

b. Implement the up-down-permute function, which takes of list of unique integers and

generates all of permutations that are up-down permutations. Your implementation

should take time that is proportional to the length of the answer—in particular, you may

not generate all of the permutations and then filter out those that fail the predicate from

part a. You may assume that the list being permuted is comprised of integers, and that

each integer appears exactly once. You needn’t generalize your implementation for various

comparison functions; just assume that less than ( < ) and greater than ( > ) can be hard-coded

into your implementation. This is difficult, but quite doable if you define down-up-permute

as well and implement each in terms of the other. Feel free to make use of the remove

function from lecture, which returns a list identical to the one specified, except that all

instances of a specified element have been omitted. You should use mapping instead of

exposed car-cdr recursion.

;; Function: up-down-permute ;; -------------------------- ;; up-down-permute generates all those permutations of a list that ;; just happen to be up-down permutations. ;; ;; Examples: (remove 3 '(1 2 3 4 5 4 3 2 1)) - > (1 2 4 5 4 2 1) ;; (up-down-permute '()) - > (()) ;; (up-down-permute '(1)) - > ((1)) ;; (up-down-permute '(1 2)) - > ((1 2)) ;; (up-down-permute '(1 2 3)) - > ((1 3 2) (2 3 1)) ;; (up-down-permute '(1 2 3 4 5)) - > ;; ((1 3 2 5 4) (1 4 2 5 3) (1 4 3 5 2) (1 5 2 4 3) (1 5 3 4 2) ;; (2 3 1 5 4) (2 4 1 5 3) (2 4 3 5 1) (2 5 1 4 3) (2 5 3 4 1) ;; (3 4 1 5 2) (3 4 2 5 1) (3 5 1 4 2) (3 5 2 4 1) ;; (4 5 1 3 2) (4 5 2 3 1)) (define (up-down-permute num-list) (

elements are low-high-low and then recurring on the cdr of the cdr using the original

predicate.

(define (is-up-down? ls comp) (or (null? ls) (null? (cdr ls)) (and (comp (car ls) (cadr ls)) (or (null? (cddr ls)) (and (comp (caddr ls) (cadr ls)) (is-up-down? (cddr ls) comp))))))

You could even use mutual recursion and define a sister is-down-up? function. In fact,

the second half of this problem does exactly that. 

b.

;; Function: up-down-permute ;; -------------------------- ;; up-down-permute generates all those permutations of a list that ;; just happen to be up-down permutations. ;; ;; Examples: (remove 3 '(1 2 3 4 5 4 3 2 1)) -> (1 2 4 5 4 2 1) ;; (up-down-permute '()) -> (()) ;; (up-down-permute '(1)) -> ((1)) ;; (up-down-permute '(1 2)) -> ((1 2)) ;; (up-down-permute '(1 2 3)) -> ((1 3 2) (2 3 1)) ;; (up-down-permute '(1 2 3 4 5)) -> ;; ((1 3 2 5 4) (1 4 2 5 3) (1 4 3 5 2) (1 5 2 4 3) (1 5 3 4 2) ;; (2 3 1 5 4) (2 4 1 5 3) (2 4 3 5 1) (2 5 1 4 3) (2 5 3 4 1) ;; (3 4 1 5 2) (3 4 2 5 1) (3 5 1 4 2) (3 5 2 4 1) ;; (4 5 1 3 2) (4 5 2 3 1)) (define (construct-permute-generator comp inverted-permute ls) (lambda (number) (apply append (map (lambda (permutation) (if (comp number (car permutation)) (list (cons number permutation)) '())) (inverted-permute (remove ls number)))))) (define (up-down-permute ls) (if (<= (length ls) 1) (list ls) (apply append (map (construct-permute-generator < down-up-permute ls) ls)))) (define (down-up-permute ls) (if (<= (length ls) 1) (list ls) (apply append (map (construct-permute-generator > up-down-permute ls) ls))))

CS107 Handout 39 Spring 2008 June 2, 2008

Section Handout: Python

Problem 1: Jane Austen’s Favorite Word

Project Gutenberg is an open-source effort intended to legally distribute electronic copies

of thousands of books no longer under copyright. So, if you’re tired of coding in spite of

the strong Internet connection, you might download yourself a little Franz Kafka by

visiting:

http://www.gutenberg.org/files/5200/5200.txt

and e-flip through Metamorphosis to pass the time.

A quick scan of www.gutenberg.org reveals that virtually all of Jane Austen’s

novels—Emma, Lady Susan, Love and Friendship, Northanger Abbey, Persuasion, Price

and Prejudice, and Sense and Sensibility—are available in plain text format. Naturally,

this prompts you to wonder what everyone else is wondering: What’s Jane Austen’s

favorite word?

Given an array of URLs, write a Python function getFavoriteWord that reads in all of

the plain text documents addressed by the URLs, compiles a huge frequency map of all

words she uses anywhere in any of the texts, and returns the most commonly occurring

word. Only count a word if it’s all lowercase letters, and assume the favorite word is the

one with the highest score, where the score of a word is equal to freqlen , where freq is

the word’s frequency and len is the word’s length. For simplicity, assume all

punctuation marks are separated from real words by whitespace.

See the last page of the section handout for a list of all dictionary methods. (You’ll want

to focus on the get and operator[] methods.)

Pulls all of the contents from each of the URLs in the 'urls' list,

and returns what appears to be the favorite word, where the

metric for what favorite means is outlined above

def getFavoriteWord(urls):

So, if the following were fed to standard input:

then your program would print the maximum number of points one can get by

optimally distributing pebbles while respecting the two rules, which would be this:

Python mutable sequence API

Python dictionary API

The above tables were lifted from http://docs.python.org/lib/typesseq-

mutable.html and http://docs.python.org/lib/typesmapping.html.

if instream.code != 200: return [] lines = instream.readlines() lines = map(lambda line: line.rstrip("\n"), lines) instream.close() return lines

Updates the map to include all of the individual words

in the line. The split methods takes a line and generates

a list of all those words in the line that are separated

from one another by whitespace. We're pretending that

punctuation marks hugging actual words isn't something we want to

worry about, although in practice we would really have to worry about it. :)

Note the use of the dictionary's get method, which allows you to return

a default value whenever the key of interest isn't present.

def digestSingleLine(line, freqMap): words = line.split() for i in xrange(0, len(words)): if words[i].islower(): freq = freqMap.get(words[i], 0) + 1 freqMap[words[i]] = freq

Trivial wrapper function

def digestLines(lines, freqMap): for i in xrange(0, len(lines)): digestSingleLine(lines[i], freqMap)

Two subtasks: break down into lines, and then digest each line one by one

def digestText(url, freqMap): lines = pullLines(url) digestLines(lines, freqMap)

Pulls all of the contents from each of the URLs in the

'urls' list, and returns what apppears to be the favorite

word, where the metric for what favorite means is outlined above

def getFavoriteWord(urls): freqMap = {} for i in xrange(0, len(urls)): digestText(urls[i], freqMap) favorite = "" favoriteScore = 0 for key in freqMap.keys(): score = freqMap[key] ** len(key) if score > favoriteScore: favorite = key favoriteScore = score return favorite

Top level expressions that get executed in sequence

favoriteWord = getFavoriteWord(["http://www.gutenberg.org/dirs/etext98/pandp12.txt", "http://www.gutenberg.org/dirs/etext98/lvfnd10.txt", "http://www.gutenberg.org/dirs/etext97/lsusn11.txt", "http://www.gutenberg.org/dirs/etext94/persu11.txt", "http://www.gutenberg.org/dirs/etext94/nabby11.txt", "http://www.gutenberg.org/dirs/etext94/mansf10.txt"]) print "It appears Jane Austen really likes the word "%s"." % favoriteWord

Solution 2: Maximizing Points

You’re given an unlimited number of pebbles to distribute across an N x N game board

(N drawn from [3, 15]), where each square on the board contains some positive point

value between 10 and 99, inclusive. A 6 x 6 board might look like this:

The player distributes pebbles across the board so that:

  • At most one pebble resides in any given square.
  • No two pebbles are placed on adjacent squares. Two squares are considered

adjacent if they are horizontal, vertical, or even diagonal neighbors. There’s no

board wrap, so 44 and 61 aren’t neighbors. Neither are 33 and 75.

The goal is to maximize the number of points claimed by your placement of pebbles.

Write a program that reads in a sequence of boards from standard input and posts the

maximum number of points attainable by an optimal pebble placement for each. Each

board is expressed as a series of lines, where each line is a space-delimited series of

numbers. A blank line marks the end of each board (including the last one.)

The better solution to this problem uses memoization to reduce the running time of the

solution from something very exponential in running time to something noticeably less

exponential (though still exponential.) Don’t worry too much about the file reading

portion of the solution—focus instead on the ideal distribution of pebbles and the

Python code that helps to discover it. (See the last page of this handout for a list of all

dictionary and mutable sequence methods.)

Sample Solution

#!/usr/bin/env python import sys import copy def computeOptimalScoreForSubBoard(gameBoard, currRow, currCol, permissions, cache): if currCol >= len(gameBoard[0]): # wrap here so recursive calls are easier currRow = currRow + 1 currCol = 0 if currRow == len(gameBoard): return 0 if cache.has_key(key(currRow, currCol, permissions)): return cache[key(currRow, currCol, permissions)] permissionsWithout = copy.copy(permissions) permissionsWithout.pop(0) permissionsWithout.append(True) optimalScore = optimalScoreWithout = computeOptimalScoreForSubBoard(gameBoard, currRow, currCol + 1, permissionsWithout, cache) if (permissions[0]): permissionsWith = copy.copy(permissions) permissionsWith.pop(0) permissionsWith[-1] = False if currCol > 0: permissionsWith[-2] = False if currCol < len(gameBoard[0]) - 1: permissionsWith[0] = False permissionsWith.append(currCol == len(gameBoard[0]) - 1) optimalScoreWith = gameBoard[currRow][currCol] + computeOptimalScoreForSubBoard(gameBoard, currRow, currCol + 1, permissionsWith, cache) if (optimalScoreWith > optimalScore): optimalScore = optimalScoreWith cache[key(currRow, currCol, permissions)] = optimalScore return optimalScore def computeOptimalScore(gameBoard): permissions = map(lambda x: True, range(0, len(gameBoard[0]) + 1)) cache = {} return computeOptimalScoreForSubBoard(gameBoard, 0, 0, permissions, cache) def key(currRow, currCol, permissions): return str(currRow) + " - " + str(currCol) + " - " + str(permissions) def readBoard(): gameBoard = [] for line in sys.stdin: line = line.rstrip("\n") if line == "": return gameBoard row = map(int, line.split()) gameBoard.append(row) return None while True: gameBoard = readBoard() if gameBoard == None: break print computeOptimalScore(gameBoard)