This preview shows page 1. Sign up to view the full content.
Unformatted text preview: CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. University of Waterloo CS116 Midterm Collection
2011 Oda_Eagle Production
CS115/116/125/134/135/136/241/240/246/341/343 Tutor
eaglediao@gmail.com
The following notes are relevant for all questions:
• We use the term “Scheme” as a short for “Intermediate Student Scheme with Lambda.”
• Supply exactly the parts of design recipe requested in each question. For a helper function, supply the body only.
• These abstract list function may be useful to you.
– ( map func lst ) applies func to all elements of lst in turn.
– ( filter func lst ) produces the list of all elements of lst for which func produces true.
– ( foldr func base ( list x1 … xn ) ) produces
( func x1 … ( func xn base ) ).
– ( buildlist n func ) produces ( list ( func 0 ) … ( func ( sub1 n ) ) ).
– max determines the largest of two or more numbers
– min determines the smallest of two or more numbers
– sqrt determines the positive square root of a number
– stringlength determines the length of a string
– stringappend combines two or more strings into a single string, in the order given
– checkexpect determines if two values are exactly the same, and is to be used for tests when they are requested
– ( makeposn x y ) produces a posn structure with field value x and y
– (posnx p ) and ( posny p ) produce the first and second fields of a posn p
– ( substring s p1 p2 ) produces a string containing the characters from a from postion p1 through p2 1 This Collection contains:
•
•
•
•
•
•
• 2009 Fall Midterm 1
2009 Winter Midterm 1
2009 Fall Midterm 2
2009 Winter Midterm 2
2009 Spring Midterm 1
2009 Spring Midterm 2
2010 Fall Midterm 刁一勾 CS 大课堂，常年招生，经验丰富，童叟无欺
1. 提供作业讲座，作业答疑 2. 提供考试复习，考试练习，有 past midterm 也有 final，也有猜题 3. 提供邮件答疑（免费） 详细咨询请联系刁一勾 eaglediao@gmail.com NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 1. Abstract List Functions. Implement following questions with contract and
at least one example and test. You have to use at least one abstract list function and
use lambda where appropriate.
Fall 2009 Questions, finish question 1 & 2 with following structures.
( definestruct meeting title time )
;; title is a string
;; time is a meetingtime
( definestruct meetingtime month day time )
;; month is a nat
;; day is a nat
;; time is a nat
1. Write a function meetingsontopic that consumes a list of meeting structures and a string, and
produces the list of all the meetings with that string as the title.
2. write a function reschedulesep that consumes a list of meeting structures and produces a new
list, with the same set of meetings, except that all meetings scheduled for September ( indicated
by month value 'Sep ) are moved to October ( indicated by a month value of 'Oct )
3. Write a function weirdfn which consumes a list of integers, and produces a new list in which
• all positive values in the original list have been multiplied by 1
• all negative values have been multiplied by 2, and
• all the zero values replaced by the string “happy”
For example , ( weirdfn '(2 5 1 0 10 0 3 ) produces '(2 5 2 “happy” 10 “happy” 6 ) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Winter 2009 Questions, finish question 1 & 2 with following structures.
An order is a structure ( makeorder na pr unt ), where na is a symbol and pr and unt are both
numbers. The structure definition is:
( definestruct order ( name price units ) ).
The cost of an order is the product of the price and the number of units.
A photo is a structure ( makephoto s h w ), where is a symbol and h and w are both numbers.
The structure definition is:
( definestruct photo ( subj ht wd ) ).
The area of a photo is the height (ht) times the width (wd).
You may assume these definition have already been entered:
( definesturct order ( name price units ) )
( define silverorder ( makeorder 'silver 10 10 ) )
( define goldorder ( makeorder 'gold 1000 1 ) )
( definestruct photo ( subj ht wd ) )
( define dogpic ( makephoto 'dog 5 7 ) )
( define catpic ( makephoto 'cat 8 10 ) )
( define towerpic ( makephoto 'tower 6 8 ) )
1. Write a Scheme function totalcost to compute the total cost of a list aloo, each of whose
members is an order.
2. Write a function bigsubjects that consumes a list alop each of whose members is a photo, and a
single photo,sample. Your function should produce a list of the subj of each photo in alop with
greater area than sample. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Spring 2009 Questions, finish question 1 & 2 & 3 with following structures.
A student is a structure (makestudent name id courseList) where name is a string, id is a
positive integer, and courseList is a lists of courses. A course is a structure (makecourse name
grade) where name is a string and grade is a nonnegative integer.
1. Write a function createcourselist which consumes a list of strings and a list of nonnegative
integers and produces a list of courses (where the first name and first grade are in the first
course, the second name and second grade are in the second course, and so on). You can assume
the two lists are the same length.
2. Using abstract list functions and without using local or length or more than one define, write a
function abovet which consumes an integer t and a student, and returns true if and only if that
student has at least one course in which their grade is greater than or equal to t; otherwise,
return false. For full marks, you must use an abstract list function as part of your solution.
3. Using abstract list functions and without using local or more than one define, write a function
removecourses which consumes a list of students and returns a list of pairs (i.e., each pair
being a list containing the name and id) for each student.
4. Using abstract list functions and without using local or more than one define, write the function
kmultiples which consumes two positive integers k and t and produces a list with t elements of
the form (list 0 k (* 2 k) ... (* (t1) k)). Fall 2010 Questions.
1. Write the body of the function sumofevensquares that consumes a list of natural numbers
and produces the total sum of the squares of the numbers in lst which are even.
2. Rewrite the following function by using at most one define statment( i.e. use lambda where
appropriate).
;; somesum: ( listof ( listof num ) [length >=2] ) → ( listof bool )
( define ( somesum lol )
[ ( define ( increasing? L )
( cond
[ ( < ( first L ) ( second L ) ) true ]
[ else false ] ) )
( define ( firsttwononzer? L )
( and ( zero? ( first L ) ) ( zero? ( second L ) ) ) ) ]
( map firsttwononzero? ( filter increasing? lol ) ) ) ) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 2. Concept Questions.
Queston 1. Fall 2009
Suppose a programmer has written a function with the following contract ;; fnusingfn : ( X>Y ) ( listof X ) → ( listof Y )
(a) Suppose another programmer is attempting to use fnusingfn, and writes the following ,
valid Scheme expression:
(fnusingfn stringlength ( list “good” “luck” “on” “the” “exam” ) )
I.
in a sentence or two, explain how this expression meets the contract for
the parameters to fnusingfn
II.
What will be the type of data produced by this call, based on the
contract? ( Note: we want the type of data produced, not the actual value you
think is produced ).
(b) Suppose yet another programmer is attempting to use fnusingfn and writes the following
Scheme expression. Does it meet the contract? If so, indicate the type of the output that will be
produced. If not, briefly explain how the contract is violated.
( fnusingfn ( lambda (w) ( symbol=? w 'WWW ) ) ( list 10 20 0 30 ) ) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Question 2. Quick sort, Winter 2009
Here is the code given in class for quicksort ( with some parts of the design recipe removed ).
1
;; quicksortlist : ( listof num ) → ( listof num )
2
( define ( quicksortlist lst )
3
( cond [ ( empty? lst ) empty ]
4
[ else ( local [ ( define pivot ( first lst ) )
5
( define lessthan
6
( filter ( lambda (x) ( < x pivot ) ) lst ) )
7
( define morethan
8
( filter ( lambda (x) ( > x pivot ) ) lst ) ) ]
9
( append ( quicksortlist lessthan )
10
( list pivot )
11
( quicksortlist morethan ) ) ) ] ) ) )
The correctness of quicksortlist relies on the assumption that all the numbers in lst are different
How would you change this code so that it would be correct even for a list with duplicate
entries? For example, ( quicksortlist '( 3 2 3 1 2 ) ) should produce '(1 2 2 3 3 ).
Be precise about where changes would be made ( for example, “after line 2, insert...” or “Delete
lines 45” ). Question 3. Fall 2010
Consider the following Scheme program:
(define unknown
(lambda ( x y z )
( y ( + x z ) ( list z ) ) ) )
one other useful piece of information is that unknown produces the same type as its first
parameter.
(a) write the contract for unknown. Be as specific as possible.
(b) Write the purpose for unknown.
(c) write two tests for unknown. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 3. Using function as parameters questions. Provide contract, and at least
one test, and funciton body for each of the following questions.
Question 1. Fall 2009
Write a function checkcondition which consumes three parameters: a list of numbers (nums),
and two functions, measure and verify, with the following properties
•
• measure consumes a nonempty list of numbers, and produces a single number
verify consumes a single number, and produces true if it satisfies a particular condition,
and false otherwise.
The function checkcondition produces the symbol 'empty for an empty list, 'acceptable
if verify produces true when called with (measure nums), and 'unacceptable otherwise.
Examples for checkcondition are included below: Measure produces Verify checks if this
value is For the list nums Checkcondition
should produce Minimum of list <=100 Empty 'empty Average of list >= 50 '(80 75 50 90) 'acceptable Length of list >= 10 '(80 20 30 40 0 ) 'unacceptable Question 2. Winter 2009
Write a function funcmax that consumes a function func and a nonempty list lst. The function
func is a oneargument function that produces a number. The function funcmax produces an
element elem of lst such that ( func elem ) is the largest possible. If two or more values from lst
produce the same largest number when func is applied to them, funcmax produces the one
closest to the beginning of the list. For example , ( funcmax sqr ( list 1 2 4 4 ) ) produces 4. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Question 3. Spring 2009
Using abstract list functions, write the function firstbetter which consumes two “application”
functions, one “comparison” function and a list. The “application” functions each consume one
element of the same type. The “application” functions produce the same type of element
(though not necessarily the same type as they consume). The “comparison” function consumes
two elements of the same type and produces a boolean value. The function firstbetter should
produce a list of those elements from the original list for which the “comparison” function
produces true when given the first “application” function applied on that element and the second
“application” function applied on that element.
For example, (firstbetter sqr sqrt >= (list 0 0.36 1 2)) ) produce (list 0 1 2) Question 4. Fall 2010
The function f consumes a boolean function f1, and a function f2, and a list lst, the functions f1
and f2 each consume a single parameter. f produces the list where f2 has been applied to all
elements e of lst such that ( f1 e ) produces true. Example: ( f even? add1 ( list 11 2 9 4 55 ) ) →
( list 3 5 ) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 5. Produce a function using lambda.
Question 1. Fall 2009
Write a function appendtoall which consumes a string s, and produces a oneparameter
function. The produced function consumes a list of string values, and produces a new list, with
the string s appended to each string in the given list.
For example, if appendtoall is called with “@uw.ca”, and the produced function is called
with the list '(“lmcase” “j27li” “cs116” ), it should produce the list '(“lmcase@uw.ca”
“j27li@uw.ca” “cs116@uw.ca” ). Question 2. Winter 2009
Write a function makelistadder that consumes a list of numbers lst and produces a oneargument function. That oneargument function consumes a number addend and produces the
list formed by adding addend to each element of lst. Question 3. Spring 2009
Using abstract list functions, write the function multlist that consumes a list lst of numbers and
produces a oneargument function. When that function is called with a number m, the produced
value is the list formed by multiplying m by every element of lst. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 5. Drawing Questions. Suppose the following Scheme expressions have been
entered into the Interactions window in DrScheme, in the order that appears below.
Using the memory model shown in class, draw a picture showing the assignment of
values to variables.
Question 1. Fall 2009
(a) draw memory model.
( define x 3 )
( define y x )
( define origin ( makeposn 5 7 ) )
( define dst1 ( makeposn origin 0 ) )
( define dst2 dst1 )
( define dst3 ( makeposn 5 7 ) )
(b) Suppose the following expressions are entered into the Interactions window after
expressions entered in part (a). For each expression followed by an empty box, fill the
box with what the expression produces. The first box has been filled in for you. x 3 ( set! x ( + x 4 ) )
x
y
( setposnx! origin dst3 )
( posnx dst1 )
( posnx dst2 )
( posnx dst3 )
( setposny! dst1 y )
( set! y 6 )
( posny dst1 )
( set! dst3 ( makeposn 3 6 ) )
( posnx origin )
( equal? ( posny ( posnx ( posnx
dst1 ) ) ) y ) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Question 2. Winter 2009
(a) Draw memory model
( define num1 4 )
( define num2 7 )
( define num3 num1 )
( define pt1 ( makeposn 3 0 ) )
( define pt2 ( makeposn 3 0 ) )
( define pt3 pt1 )
(b) Suppose the following expressions are entered into the Interactions window after
expressions entered in part (a). For each expression followed by an empty box, fill the
box with what the expression produces. The first box has been filled in for you. num1 4 ( set! Num1 8 )
num1
num3
( setposnx! pt1 1 )
( posnx pt1 )
( posnx pt2 )
( setposny! pt2 num2 )
( set! num2 6 )
( posny pt2 )
( set! pt3 ( makeposn 3 0 ) )
( = ( posnx pt1 ) ( posnx pt3 ) ) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Question 3. Spring 2009
(a) Draw memory diagram.
(define num1 8)
(define num2 num1)
(define pt1 (makeposn 3 0))
(define pt2 (makeposn 3 0))
(define pt3 pt1)
(define pt4 (makeposn pt1 5))
(b) Suppose the following expressions are entered into the Interactions window after
expressions entered in part (a). For each expression followed by an empty box, fill the
box with what the expression produces. The first box has been filled in for you. num1 8 (set! num1 (+ num1 8))
num1
num2
(setposnx! pt1 1)
(posnx pt1)
(posnx pt2)
(posnx pt3)
(posnx pt4)
(setposny! pt2 num2)
(set! num2 6)
(posny pt2)
(set! pt3 (makeposn 3 0))
(equal? pt1 pt3) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Queston 4. Fall 2010
(a) draw the memory diagram.
(define c1 ( makecard 8 'hearts))
(define c2 ( makecard 8 'hearts))
(define c3 c2 )
(define x 1977 )
(define y ( set! X ( + x 20 ) )
(b) consider the following starting state, write code to transfer following state to diagram
given.
(define num1 void)
(define num2 void)
(define num3 void)
(define pt1 void )
(define pt2 void )
(define pt3 void ) makeX
posn
pt1
4 7 4 num1 num2 num3 3
posn pt2
3 0 pt3 NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 6. Accumulative recursion. For each of the following questions, provide a
contract and function body.
Question 1. Fall 2009
Use accumulative recursion to write a function countsublists that consumes a list ( which can
contain any kind of elements ) and produces a number indicating the number of nonempty
sublists in the given list. If the list is empty, then return zero. As an example, ( countsublists
'((1 2) ( 3 ( 3 3 ) ) 4 ( 5 ) ) ) would produce 3. Question 2. Winter 2009
Use accumulative recursion to write a function adddigits that consumes a natural number n
and produces the sum of the digits of that number. Your solution must run in time which is
linear in the number of digits of n.
Contract:
;; adddigits: nat → nat
Examples:
;; ( adddigits 427 ) → 13
;; ( adddigits 12 ) → 3
;; ( adddigits 0 ) → 0 Question 3. Winter 2009
Use accumulative recursion to write a function smallestsum which consumes a list of natural
numbers ( where there are at least 2 numbers in the list ) and produces the smallest pairwise
sum. By “pairwise” sum, we mean the sum of two adjacent elements in the list. As an example,
consider the list ( list 1 4 2 3 8 ) : there are 4 pairwise sums. ( 1 + 4 = 5 , 4 + 2 = 6 , 2 + 3 = 5
and 3 + 8 = 11 ). In this case, the smallest pairwise sum would be 5 ( which happens to occur
twice ).
Contract:
;; smallestsum ( list of nat ) [ length >= 2 ] → nat
Examples:
;; ( smallestsum '(1 2 3 4 5 ) ) → 3
;; ( smallestsum '(1 4 2 5 1 8 1 ) → 5
;; ( smallestsum '( 100 100 ) ) → 200 NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Question 4. Spring 2009
Use accumulative recursion to write a function 2ndlargest that consumes a
list of length at least 2 containing distinct numbers and produces the second largest number in
the list. Question 5. Spring 2009
Use accumulative recursion to write a function largestdifference which
consumes a list of natural numbers (where there are at least 2 numbers in the list) and produces
the largest pairwise difference. By “pairwise” difference, we mean the absolute difference
between two adjacent elements in the list. As an example, consider the list (list 1 4 2 3 8): there
are 4 pairwise differences (1 − 4 = 3, 4 − 2 = 2, 2 − 3 = 1 and 3 − 8 = 5). In this case, the
largest pairwise difference would be 5. Note that (abs 4) ) 4 and (abs 2) ) 2. Question 6. Fall 2010
Using accumulative recursion, write the function matchingindices that consumes a natural
number n and list of natural numbers lst. The function produces a list of natural numbers
corresponding to the indices where n appears in lst.
•
•
• The values in the produces list must be in increasing order
The first item in a list has index 0
You may use reverse for this question Example:
( matchingindices 3 ( list 4 2 1 ) ) → empty
( matchingindices 10 ( list 20 10 30 ) ) → ( list 1 )
( matchingindices 7 ( list 7 2 8 7 7 ) ) → ( list 0 3 4 ) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 7. Efficiency, For each of the following Scheme functions identify the
worstcase running time as one of
•
•
• Linear ( denoted as O(n) )
quadratic ( denoted as O( n2 ) ) or
exponential ( denoted as O( 2n ) )
(a) Choose the worstcase running time of functA.
( define ( functA mylist )
( cond [ ( empty? ( rest mylist ) ) ( first mylist ) ]
[ else ( + ( first mylist )
( functA ( rest mylist ) ) ) ] ) )
(b) Choose the worstcase running of functB.
( define ( functB mylist )
( cond [ ( empty? ( rest mylist ) ) empty ]
[ else ( append ( functB ( rest mylist ) )
( list ( first mylist ) ) ) ] ) )
(c) Choose the worstcase running of functC.
( define ( functC mylist )
( cond [ ( empty? ( rest mylist ) ) ( first mylist ) ]
[ ( < ( first mylist ) ( functC ( rest mylist ) ) )
( first mylist ) ]
[ else ( functC ( rest mylist ) ) ] ) )
(d) Choose the worstcase running time of functA.
( define ( functA mylist )
( local ( define ( helper al )
( cond [ ( empty? Al ) 0 ]
[ else ( + ( first al ) ( helper ( rest al ) ) ] ) ) ) )
( cond [ ( empty? mylist ) empty ]
[ else ( cons ( helper mylist )
( functA ( rest mylist ) ) ) ) ) ) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past.
(e) Choose the worstcase running of functB.
( define ( functB mylist )
( cond [ ( empty? ( rest mylist ) ) empty ]
[ else ( cons ( first mylist ) ( functB ( rest mylist ) ) ] ) ) ) )
(f) Choose the worstcase running of functC.
( define ( functC mylist )
( cond [ ( empty? ( rest mylist ) ) ( first mylist ) ]
[ ( < ( first mylist ) ( functC ( rest mylist ) ) )
( first mylist ) ]
[ else ( functC ( rest mylist ) ) ] ) )
(g) Circle the worstcase running time of functA.
(define (functA mylist)
(cond [(empty? mylist) empty]
[else (cons (rest mylist)
(functA (rest mylist)))]))
(h) Circle the worstcase running time of functB.
(define (functB mylist)
(local [(define (helper al)
(cond [(empty? al) 0]
[else (+ (helper (rest al)) (first al))]))]
(cond [(empty? mylist) empty]
[else (cons (helper mylist)
(functB (rest mylist)))])))
(i) Circle the worstcase running time of functC.
(define (functC mylist)
(cond [(empty? (rest mylist)) (first mylist)]
[(> (first mylist) (functC (rest mylist)))
(first mylist)]
[(= (first mylist) (functC (rest mylist)))
(first mylist)]
[else (functC (rest mylist))])) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 8. Mutation, provide at least one test that differ from the example.
Question 1. Fall 2009
Suppose you have the following state variables defined:
( define m 3 )
( define n 6 )
Write a Scheme function mymutate that consumes two functions f1 and f2. F1
consumes one parameter and produces a number; f2 consumes two parameters of the
same type and produces that same type. If the result of applying f1 to m is larger than the
result of applying f1 to n, then the function mymutate should mutate m to the result of
applying f2 to m and n ( that is, m will be the first parameter of f2, and n will be the
second parameter of f2 );
otherwise, the function mutates n to the result of applying f2 to n and m( that is, n will
be the first parameter of f2, and m will be the second parameter of f2 ).
As an example, suppose m is 3 and n is 6. f1 is the Scheme buildin sqr function and f2
is the + function, since ( sqr 3 ) < ( sqr 6 ), the mymutate function will mutate n to ( + 6
3 ), therefore, the value of n becomes 9 after applying the function. Question 2. Winter 2009
( define x 1 )
( define y 1 )
Write a Scheme function functmutation that consumes two functions f1 and f2, each of
which consume two elements ( both of the same type ) and produce one element ( which
has the same type as the consumed type ). The function functmutation should alter x to
the result of applying f1 to x and y. and it should alter y to the result of applying f2 to x
and y.
Examples:
;; if x has the value 1 and y has the value of 1, and we evaluate
;; ( functmutation + quotient ) , then x has the value 2 and
;; y has the value 1. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Question 3. Spring 2009
Suppose you have the state variables x and y defined, and that they are the same
type. Write a Scheme function functmutation that consumes two functions f1 and f2, each of
which consume one element and produce a number. The function functmutation should mutate
x to the maximum of applying f1 to x and applying f2 to y, and mutate y to the sum of applying
f2 to x and f1 to y. Question 4. Fall 2010
Write the function swapsuit that consumes two cards c1 and c2 and produces (void). The
function mutates the suit of the two cards such that c1 has the suit of c2, and c2 has the suit of
c1. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 9. Tracing
Question 1. Fall 2009
Consider the code:
;; mystery: nat[ >= 1 ] → ( listof nat )
( define ( mystery n )
( local ( ( define ( acchelper next remain lst )
( cond
[ ( = remain 1 ) lst ]
[ ( > next remain ) ( cons remain lst ) ]
[ ( zero? ( remainder remain next ) )
( acchelper next
( quotient remain next )
( cons next lst ) ) ]
[ else ( acchelper ( add1 next ) remain lst ) ] ) ) )
( acchelper 2 n empty ) ) )
for each of the following test cases, give the output of mystery
(a) ( mystery 1 ) (b) ( mystery 2 ) (c) ( mystery 12 ) (d) ( mystery 29 ) Question 2. Winter 2009
;; mystery: ( list of nat( >= 1 ) ) → nat
( define ( mystery alopn )
( local
;; stripk: nat ( list of nat ( >=1 ) ) → ( list of nat ( >=1 ) )
;; Purpose: stripk removes the first k elements from the provided list; if there are
;; k or fewer elements in the list, the empty list is returned
;; Examples: ( stripk 0 ( list 1 2 3 ) ) → ( list 1 2 3 )
;;
( stripk 2 ( list 1 2 3 ) ) → ( list 3 )
( define ( stripk k lst )
( cond ( ( zero? K ) lst )
( ( empty? Lst ) empty )
( else ( stripk ( sub1 k ) ( rest lst ) ) ) ) ) )
( cond ( ( empty? Alopn ) 0 )
( else ( add1 ( mystery ( stripk ( first alopn ) alopn ) ) ) ) ) )
for each of the following test cases, give the output of mystery
(a) ( mystery empty ) (b) ( mystery ( list 1 10 9 8 ) ) (c) ( mystery ( list 1 2 10 3 1 1 1 ) )
NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Question 3. Spring 2009
;; mystery: nat[>0] ! (listof nat)[length=2]
(define (mystery n)
(local
[(define (mysteryhelp num acc)
(cond
[(even? num) (mysteryhelp (/ num 2) (add1 acc))]
[else (list num acc)]))]
(mysteryhelp n 0)))
For each of the following test cases, give the output of mystery.
(a) (mystery 9) )
(b) (mystery 10) )
(c) (mystery 36) )
(d) (mystery 480) ) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 10. Basic Python
Question 1. Fall 2010
assume base on following code:
a = 11
b=6
c = 9.2
L1 = [a,b]
L2 = [a,b,c,c,b,a]
s1 = “tabby”
Python statement Output print (a+b),c
print int(c)
print a/b
print float(a/b)
print a%b
print type(a) == type(c)
print len(L1)
print L2[2:5]
print s1[1]
print s1[1:]
print (a>=L1[1])
print range(3,7)
print range(4,1,1)
print 3*s1 NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 11. Basic Python programming.
Question 1. Fall 2010
Write the python function division which consumes two positive integers numerator and
denominator ( with numerator >= denominator ) and prints out information about the
quotient and remainder of these two numbers. For example, division(10,3) should print
out
10/3 is 3 with remainder 1
and division(12,6) should print out:
12/6 is 2 with remainder 0 NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 12. Other questions. Provide contract, example and test and function
body for each of the following questions.
Question 1. Spring 2009
Write a function listlistpick which consumes a list of list of numbers and a natural
number n 1 and produces the nth number in the list of lists (counting each number in
each list), or false if there aren’t enough numbers in the list of lists. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past. Part 13. Super duper Challenge Questions from Winter 2010 take home
midterm.
Question 1. Create a Scheme function vendingmachine that simulates the actions of a vending
machine. The program contains three state variables: coinbox (representing the total amount of
money inserted into the vending machine), numchips (representing the number of bags of chips
in the machine) and numbars (representing the number of chocolate bars in the machine). The
program also contains constants that indicate the price of chips and chocolate bars. The function
vendingmachine will consume a number equal to the amount of a coin (one of 0.05, 0.10, 0.25,
1.00, 2.00) or a symbol indicating a purchase (one of 'chips or 'bar). The function will produce
the following:
•
• • • If the value entered is a number, nothing is produced, but the coinbox is updated
accordingly.
If the value entered is a symbol representing a food item with an inventory of 0, the
function produces the string "Sold out" regardless of how much money is in the coinbox. (The coinbox will be unaffected.)
If the value entered is a symbol and the coinbox contains enough money for the
purchase matching the symbol, the function will produce the change owed for the
purchase, the coinbox should be reset to 0 and the appropriate food state variable is
reduced by 1.
If the value entered is a symbol and the coinbox does not contain enough money, the
function will produce the string "Insufficient funds" . (The coinbox will be unaffected
either way.) For example, suppose the following sequence of function calls occurred:
(set! numbars 5)
(set! coinbox 0)
(vendingmachine 2.00)
(vendingmachine 'bar)
Then the final function call would produce 0.5, value of coinbox would be 0, and the
value of numbars would be 4.
You may assume that all input to the function will be valid (that is, all the numbers will
be greater than 0, and any symbol will be either 'chips or 'bar.)
Complete your solution without adding any extra state variables. You may use local
variables in the body of your function. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past.
Question 2. This question uses the structures athlete and winners, defined below:
(definestruct athlete (name country placement))
;; An athlete is a structure (makeathlete n c p) where
;; n is a string (athlete's name), c is a string (country the athlete represents)
;; p is a natural number (place the athlete finished in the competition) or
;; a symbol (eg. 'DNF indicating the athlete did not finish the competition or
;; 'WD indicating the athlete withdrew from the competition before it started)
(Note this is a slightly different definition than the one used on midterm one)
(definestruct winners (description gold silver bronze))
;; A winners is a structure (makewinners d g s b), where
;; d is a string (description or name of the athletic competition)
;; g,s,b are athletes (g, for gold, is the athlete who placed first,
;; s, for silver, is the athlete who placed second, and b, for bronze,
;; is the athlete who placed third in the competition).
Create a Scheme function called removecheater that consumes a string (representing the name
of a cheater), a winners structure (representing the medalists in the event), and an athlete
(representing the fourth place finisher in the event in which the winners competed.) If the name
of the cheater is one of the medalists, the placement of that athlete will be changed to 'DQ, and
everyone else will move up one place in the standings. For example, if the gold medalist is the
cheater, then the placement of the former gold medalist changes to 'DQ, the silver medalist
moves to the gold position (and their placement changes to 1), the bronze medalist moves to the
silver position (and their placement changes to 2), and the fourth place finisher moves to the
bronze position (and their placement changes to 3). The gold, silver, and bronze fields of the
winners structure should also be updated appropriately.
If the name of the cheater is neither a medalist nor the fourth place finisher, nothing will change.
In this case the function should produce the string "No change". In all other cases the function
should produce (void).
You may not use the makewinners or makeathlete functions in the body of the removecheater
function (or any helper functions you write). However these may be used within your test cases. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past.
Question 3. For this question, you will write a Scheme function hassubstring?. This function
consumes two strings, text and pattern, and will produce true if pattern is a substring of text and
false otherwise.
We can immediately determine that pattern is a substring of text if the two strings are equal, and
we can immediately determine that pattern is not a substring of text if:
•
• text is shorter than pattern, or
text is the same length as pattern but the two strings are not equal. Otherwise we consider the following cases. Let left be the first half of text and let right be the
second half of text (if the length of text is odd, then make left one character shorter than right).
We can determine that pattern is a substring of text if:
•
•
•
• pattern is a substring of left, or
pattern is a substring of right, or
pattern is a substring of text such that text has its first character removed, or
pattern is a substring of text such that text has its last character removed. Note that the last two cases are necessary because it is possible for pattern to be a substring of
text but be a substring of neither left nor right (for example, when text is “telephones” and
pattern is “leph”).
Your solution must use generative recursion to implement the algorithm exactly as it is
described in this question, even if you can think of an alternate way to solve the problem.
Examples:
(hassubstring? “abc” “abc”) => true
(hassubstring? “telephones” “leph”) => true
(hassubstring? “quick” “xy”) => false
(hassubstring? “011000101101” “111”) => false NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past.
Question 4. Consider the four functions reversesearch, sumofdivisors, growduplicates, and
mysterysort. For each of these functions, state:
•
• The best case running time of the function along with a brief justification, and
The worst case running time of the function along with a brief justification. If the best case running time and the worst case running time for a function are different, you
must also provide:
•
• An input value on which the function achieves its best case running time, and
An input value on which the function achieves its worst case running time. When giving the best case running time of a function, you are not allowed to select the size of
the input. Specifically, do not make statements such as “the best case is when the list is empty”
or “the best case is when the list has length one.” The size of the input, n, is always considered
to be an arbitrary value.
The contract for each function (and local helper function) appears in bold. We have omitted the
purpose, examples, and test cases for all functions; this is to encourage you to thoroughly read
and trace the code itself to understand exactly how the function works. The ability to trace a
function on a variety of input values is of great benefit when determining its best case and worst
case running times. You may make the following assumptions for this question:
All of the running times will be one of the following:
•
•
•
• Constant (also expressed as O(1))
Linear (also expressed as O(n))
Quadratic (also expressed as O(n2))
Exponential (also expressed as O(2n)) The function reverse has linear running time
; reversesearch: (listof any) any → boolean
(define (reversesearch lst target)
(cond
[(empty? lst) false]
[(equal? (first lst) target) true]
[else (reversesearch (reverse (rest lst)) target)])) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past.
; sumofdivisors: nat → nat
(define (sumofdivisors n)
(foldr + 0
(filter (lambda (y) (zero? (remainder n y)))
(buildlist n (lambda (x) (add1 x))))))
; growduplicates: (listof X) → (listof X)
(define (growduplicates lst)
(cond
[(empty? lst) empty]
[(= 1 (length lst)) empty]
[(empty? (filter (lambda (x) (equal? x (first lst))) (rest lst)))
(growduplicates (rest lst))]
[else (append (growduplicates (rest lst))
(list (first lst)) (growduplicates (rest lst)))]))
; mysterysort: (listof X)[nonempty] → (listof X)[nonempty]
; The elements of type X must be comparable with < and >
(define (mysterysort lst)
(local
; partition: (listof X) (listof (listof X)) (listof X)[nonempty]
; → (listof (listof X))[nonempty]
; The elements of type X must be comparable with < and >
[(define (partition lst0 listoflists nextlist)
(cond
[(empty? lst0)
(reverse (cons (reverse nextlist) listoflists))]
[(> (first lst0) (first nextlist))
(partition (rest lst0) listoflists
(cons (first lst0) nextlist))]
[else (partition (rest lst0)
(cons (reverse nextlist) listoflists)
(list (first lst0)))])) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past.
; merge: (listof X) (listof X) → (listof X)
; The elements of type X must be comparable with < and >
(define (merge lst1 lst2)
(cond
[(empty? lst1) lst2]
[(empty? lst2) lst1]
[(<= (first lst1) (first lst2))
(cons (first lst1) (merge (rest lst1) lst2))]
[else (cons (first lst2) (merge lst1 (rest lst2)))]))]
(foldr merge empty (partition (rest lst) empty (list (first lst)))))) NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past.
Question 5. Create a Python function identify_triangle that prompts the user to enter three
positive integer values in ascending order: a, b, and c. These values represent the lengths of the
sides of a triangle. If the length of the longest side is greater than or equal to the sum of the
lengths of the two smaller sides, the triangle is considered invalid. A valid triangle can be
categorized as one of the following based on the lengths of its sides:
•
•
• an equilateral triangle has three equal sides
an isosceles triangle has two equal sides
a scalene triangle has no equal sides A triangle can also be categorized as one of the following relating to the interior angles:
•
•
• a rightangled triangle has sides where c2 = a2 + b2 where a, b, and c are the lengths of
the sides of the triangle
an acute triangle has sides where c2 < a2 + b2 where a, b, and c are the lengths of the
sides of the triangle
an obtuse triangle has sides where c2 > a2 + b2 where a, b, and c are the lengths of the
sides of the triangle Your function should print invalid if the triangle is invalid. Otherwise, it should print the
category of the triangle based on its side lengths (equilateral, isosceles, or scalene) followed by
the category of the triangle based on its interior angles (rightangled, acute, or obtuse).
Your solution should use the prompts provided in the starter file. Also, whenever you are
working with strings in your programs, it is very important to be precise. All strings that are
printed should be lower case and without any extra whitespace. If there is more than one string
being printed, each string should appear on its own line. Do not print out any extra blank lines.
Three sample runs of the program are shown below. Note the use of bold to indicate the values
entered by the user while the program is executing. You may assume that the user will always
enter positive integer values.
3,3,10 → invalid
5,5,8 → isosceles,obtuse
3,4,5 → scalene, rightangled NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: eaglediao@gmail.com,
more than 4 years of experience and around 400 students in the past.
Question 6. Decimal numbers, or base 10 numbers, are written using 10 possible digits.
Numbers can
be represented with any base. For example binary numbers, or base 2 numbers, are written
using just two digits: 0 and 1. The binary number 1101 is equivalent to the decimal number 13.
The number 200 in base 5 is 1300. Create a Python function called convert_base that will
consume a nonnegative integer and an integer between 2 and 9 inclusive, and produce a string
representing the number in the new base. Note that 0 is the same number in any base.
To convert a number to a different base, you need to continuously divide by the base until you
reach 0 and record the remainder each time. Then write the remainders in reverse order.
Your solution must use recursion; it may not use loops.
Example 1: Converting 13 to base 2
13/2 = 6 remainder 1
6/2 = 3 remainder 0
3/2 = 1 remainder 1
1/2 = 0 remainder 1
Looking at the remainders in reverse, this produces 1101 in base 2, and this is the
equivalent of 13 in base 10.
Example 2: Converting 500 to base 7
500/7 = 71 remainder 3
71/7 = 10 remainder 1
10/7 = 1 remainder 3
1/7 = 0 remainder 1
Looking at the remainders in reverse, this produces 1313 in base 7, and this is the
equivalent of 500 in base 10. NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料，后果自负 ...
View Full
Document
 Spring '08
 CELMIN

Click to edit the document details