Cs 116 Midterm Collection

February 17, 2018 | Author: Hamad Javed | Category: Elementary Mathematics, Mathematics
Share Embed Donate


Short Description

cs 116 uwaterloo midterm practice...

Description

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], 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 [email protected] 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 x-1 … x-n ) ) produces ( func x-1 … ( func x-n base ) ). – ( build-list 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 – string-length determines the length of a string – string-append combines two or more strings into a single string, in the order given – check-expect determines if two values are exactly the same, and is to be used for tests when they are requested – ( make-posn x y ) produces a posn structure with field value x and y – (posn-x p ) and ( posn-y 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 2011 Winter Midterm

刁一勾 CS 大课堂,常年招生,经验丰富,童叟无欺 1. 提供作业讲座,作业答疑 2. 提供考试复习,考试练习,有 past midterm 也有 final,也有猜题 3. 提供邮件答疑(免费) 详细咨询请联系刁一勾 [email protected]

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], 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. ( define-struct meeting title time ) ;; title is a string ;; time is a meeting-time ( define-struct meeting-time month day time ) ;; month is a nat ;; day is a nat ;; time is a nat 1. Write a function meetings-on-topic 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 reschedule-sep 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 weird-fn 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 , ( weird-fn '(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: [email protected], 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 ( make-order na pr unt ), where na is a symbol and pr and unt are both numbers. The structure definition is: ( define-struct 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 ( make-photo s h w ), where is a symbol and h and w are both numbers. The structure definition is: ( define-struct 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: ( define-sturct order ( name price units ) ) ( define silverorder ( make-order 'silver 10 10 ) ) ( define goldorder ( make-order 'gold 1000 1 ) ) ( define-struct photo ( subj ht wd ) ) ( define dogpic ( make-photo 'dog 5 7 ) ) ( define catpic ( make-photo 'cat 8 10 ) ) ( define towerpic ( make-photo 'tower 6 8 ) ) 1. Write a Scheme function total-cost to compute the total cost of a list aloo, each of whose members is an order. 2. Write a function big-subjects 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: [email protected], 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 (make-student 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 (make-course name grade) where name is a string and grade is a non-negative integer. 1. Write a function create-course-list which consumes a list of strings and a list of non-negative 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 above-t 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 remove-courses 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 k-multiples which consumes two positive integers k and t and produces a list with t elements of the form (list 0 k (* 2 k) ... (* (t-1) k)).

Fall 2010 Questions. 1. Write the body of the function sum-of-even-squares 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). ;; some-sum: ( listof ( listof num ) [length >=2] ) → ( listof bool ) ( define ( some-sum lol ) [ ( define ( increasing? L ) ( cond [ ( < ( first L ) ( second L ) ) true ] [ else false ] ) ) ( define ( first-two-nonzer? L ) ( and ( zero? ( first L ) ) ( zero? ( second L ) ) ) ) ] ( map first-two-nonzero? ( filter increasing? lol ) ) ) )

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], more than 4 years of experience and around 400 students in the past.

Winter 2011 Questions (define-struct contestant ( name contest-num class-name ) ) 1. use only filter. The function class-tally consumes a string class-name, which is the name of a class name, and aloc, which is a list of contestant structures. It produces a list of all the elements in aloc whose class is class-name. 2. use only foldr. The function contest-total consumes cnum, which is a programming contest number ( 1 ,2,3,4 or 5 ) and aloc, which a list of contestants, it produces the number of elements in aloc participating in the contest with number cnum 3. use only build-list. Use build-list expression so that it evaluates to a list containing all the natural number from 0 to n-1 in decreasing order. That is, the expression evaluate to ( list n -1 n 2 … 2 1 0 ) assume that n >= 1 4. use only build-list. Use build-list expression so that it evaluates to a list contatining n bollean values as follows. If we index the list elements from 0 to n-1 then the kth element in the produced list will be true if k is divisible by 2 or 3 and false otherwise.

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], 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 ;; fn-using-fn : ( X->Y ) ( listof X ) → ( listof Y ) (a) Suppose another programmer is attempting to use fn-using-fn, and writes the following , valid Scheme expression: (fn-using-fn string-length ( list “good” “luck” “on” “the” “exam” ) ) I. in a sentence or two, explain how this expression meets the contract for the parameters to fn-using-fn 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 fn-using-fn 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. ( fn-using-fn ( 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: [email protected], 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 ;; quicksort-list : ( listof num ) → ( listof num ) 2 ( define ( quicksort-list lst ) 3 ( cond [ ( empty? lst ) empty ] 4 [ else ( local [ ( define pivot ( first lst ) ) 5 ( define less-than 6 ( filter ( lambda (x) ( < x pivot ) ) lst ) ) 7 ( define more-than 8 ( filter ( lambda (x) ( > x pivot ) ) lst ) ) ] 9 ( append ( quicksort-list less-than ) 10 ( list pivot ) 11 ( quicksort-list more-than ) ) ) ] ) ) ) The correctness of quicksort-list 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, ( quicksort-list '( 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 4-5” ).

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: [email protected], 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 check-condition which consumes three parameters: a list of numbers (nums), and two functions, measure and verify, with the following properties • •

measure consumes a non-empty 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 check-condition produces the symbol 'empty for an empty list, 'acceptable if verify produces true when called with (measure nums), and 'unacceptable otherwise. Examples for check-condition are included below:

Measure produces

Verify checks if this value is

For the list nums

Check-condition should produce

Minimum of list

= 2 ] → nat Examples: ;; ( smallest-sum '(1 2 3 4 5 ) ) → 3 ;; ( smallest-sum '(1 4 2 5 1 8 1 ) → 5 ;; ( smallest-sum '( 100 100 ) ) → 200

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], more than 4 years of experience and around 400 students in the past.

Question 4. Spring 2009 Use accumulative recursion to write a function 2nd-largest 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 largest-difference which consumes a list of natural numbers (where there are at least 2 numbers in the list) and produces the largest pair-wise difference. By “pair-wise” 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 pair-wise differences (|1 − 4| = 3, |4 − 2| = 2, |2 − 3| = 1 and |3 − 8| = 5). In this case, the largest pair-wise difference would be 5. Note that (abs -4) ) 4 and (abs 2) ) 2.

Question 6. Fall 2010 Using accumulative recursion, write the function matching-indices 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: ( matching-indices 3 ( list 4 2 1 ) ) → empty ( matching-indices 10 ( list 20 10 30 ) ) → ( list 1 ) ( matching-indices 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: [email protected], 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 worst-case running time as one of • • •

Linear ( denoted as O(n) ) quadratic ( denoted as O( n2 ) ) or exponential ( denoted as O( 2n ) ) (a) Choose the worst-case running time of funct-A. ( define ( funct-A mylist ) ( cond [ ( empty? ( rest mylist ) ) ( first mylist ) ] [ else ( + ( first mylist ) ( funct-A ( rest mylist ) ) ) ] ) ) (b) Choose the worst-case running of funct-B. ( define ( funct-B mylist ) ( cond [ ( empty? ( rest mylist ) ) empty ] [ else ( append ( funct-B ( rest mylist ) ) ( list ( first mylist ) ) ) ] ) ) (c) Choose the worst-case running of funct-C. ( define ( funct-C mylist ) ( cond [ ( empty? ( rest mylist ) ) ( first mylist ) ] [ ( < ( first mylist ) ( funct-C ( rest mylist ) ) ) ( first mylist ) ] [ else ( funct-C ( rest mylist ) ) ] ) ) (d) Choose the worst-case running time of funct-A. ( define ( funct-A mylist ) ( local ( define ( helper al ) ( cond [ ( empty? Al ) 0 ] [ else ( + ( first al ) ( helper ( rest al ) ) ] ) ) ) ) ( cond [ ( empty? mylist ) empty ] [ else ( cons ( helper mylist ) ( funct-A ( rest mylist ) ) ) ) ) )

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], more than 4 years of experience and around 400 students in the past. (e) Choose the worst-case running of funct-B. ( define ( funct-B mylist ) ( cond [ ( empty? ( rest mylist ) ) empty ] [ else ( cons ( first mylist ) ( funct-B ( rest mylist ) ) ] ) ) ) ) (f) Choose the worst-case running of funct-C. ( define ( funct-C mylist ) ( cond [ ( empty? ( rest mylist ) ) ( first mylist ) ] [ ( < ( first mylist ) ( funct-C ( rest mylist ) ) ) ( first mylist ) ] [ else ( funct-C ( rest mylist ) ) ] ) ) (g) Circle the worst-case running time of funct-A. (define (funct-A mylist) (cond [(empty? mylist) empty] [else (cons (rest mylist) (funct-A (rest mylist)))])) (h) Circle the worst-case running time of funct-B. (define (funct-B mylist) (local [(define (helper al) (cond [(empty? al) 0] [else (+ (helper (rest al)) (first al))]))] (cond [(empty? mylist) empty] [else (cons (helper mylist) (funct-B (rest mylist)))]))) (i) Circle the worst-case running time of funct-C. (define (funct-C mylist) (cond [(empty? (rest mylist)) (first mylist)] [(> (first mylist) (funct-C (rest mylist))) (first mylist)] [(= (first mylist) (funct-C (rest mylist))) (first mylist)] [else (funct-C (rest mylist))]))

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], more than 4 years of experience and around 400 students in the past. (j) ( define ( all-same? nums ) ( cond [ ( empty? nums) true ] [ ( empty? ( rest nums ) ) true ] [ else ( and ( = ( first nums ) ( second nums ) ) ( all-same? ( rest nums ) ) ) ] ) ) (k) ( define ( f n ) ( cond [(=n0)5] [ else ( + 1 ( f ( sub1 n ) ) ( f ( sub1 n ) ) ) ] ) ) (l) ( define ( silly nums ) ( not ( = ( first nums ) ( fifth nums ) ) ) )

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], 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 my-mutate 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 my-mutate 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 build-in sqr function and f2 is the + function, since ( sqr 3 ) < ( sqr 6 ), the my-mutate 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 funct-mutation 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 funct-mutation 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 ;; ( funct-mutation + 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: [email protected], 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 funct-mutation that consumes two functions f1 and f2, each of which consume one element and produce a number. The function funct-mutation 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 swap-suit 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: [email protected], 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 ( acc-helper next remain lst ) ( cond [ ( = remain 1 ) lst ] [ ( > next remain ) ( cons remain lst ) ] [ ( zero? ( remainder remain next ) ) ( acc-helper next ( quotient remain next ) ( cons next lst ) ) ] [ else ( acc-helper ( add1 next ) remain lst ) ] ) ) ) ( acc-helper 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 ;; strip-k: nat ( list of nat ( >=1 ) ) → ( list of nat ( >=1 ) ) ;; Purpose: strip-k 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: ( strip-k 0 ( list 1 2 3 ) ) → ( list 1 2 3 ) ;; ( strip-k 2 ( list 1 2 3 ) ) → ( list 3 ) ( define ( strip-k k lst ) ( cond ( ( zero? K ) lst ) ( ( empty? Lst ) empty ) ( else ( strip-k ( sub1 k ) ( rest lst ) ) ) ) ) ) ( cond ( ( empty? Alopn ) 0 ) ( else ( add1 ( mystery ( strip-k ( 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: [email protected], 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 (mystery-help num acc) (cond [(even? num) (mystery-help (/ num 2) (add1 acc))] [else (list num acc)]))] (mystery-help 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: [email protected], 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: [email protected], 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: [email protected], 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 list-list-pick 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.

Question 2. Winter 2011 A word is string of only lowercase letter. A pattern is a string of only lowercase letters and the letter “X”. A pattern matches the word obtained by replacing every instance of “X” in the pattern with 3 copies of the letter “x”. For example, the pattern “aXc” matches the word “axxxc”, the pattern “abcXxXq” matches the word “abcxxxxxxxq”, the pattern “” matches the word “”, and the pattern “abcxyz” matches the word “abcxyz”. However, the pattern “aXc” does not match the word “axc” and the pattern “aX” does not each the word “axxxbcd”. Complete the function matches? That consumes a word w and a pattern p and produces true if p matches and false otherwise.

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], 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 vending-machine that simulates the actions of a vending machine. The program contains three state variables: coin-box (representing the total amount of money inserted into the vending machine), num-chips (representing the number of bags of chips in the machine) and num-bars (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 vending-machine 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 coin-box 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 coin-box will be unaffected.) If the value entered is a symbol and the coin-box contains enough money for the purchase matching the symbol, the function will produce the change owed for the purchase, the coin-box should be reset to 0 and the appropriate food state variable is reduced by 1. If the value entered is a symbol and the coin-box does not contain enough money, the function will produce the string "Insufficient funds" . (The coin-box will be unaffected either way.)

For example, suppose the following sequence of function calls occurred: (set! num-bars 5) (set! coin-box 0) (vending-machine 2.00) (vending-machine 'bar) Then the final function call would produce 0.5, value of coin-box would be 0, and the value of num-bars 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: [email protected], 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: (define-struct athlete (name country placement)) ;; An athlete is a structure (make-athlete 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) (define-struct winners (description gold silver bronze)) ;; A winners is a structure (make-winners 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 remove-cheater 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 make-winners or make-athlete functions in the body of the remove-cheater 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: [email protected], more than 4 years of experience and around 400 students in the past. Question 3. For this question, you will write a Scheme function has-substring?. 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: (has-substring? “abc” “abc”) => true (has-substring? “telephones” “leph”) => true (has-substring? “quick” “xy”) => false (has-substring? “011000101101” “111”) => false

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], more than 4 years of experience and around 400 students in the past. Question 4. Consider the four functions reverse-search, sum-of-divisors, grow-duplicates, and mystery-sort. 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 ; reverse-search: (listof any) any → boolean (define (reverse-search lst target) (cond [(empty? lst) false] [(equal? (first lst) target) true] [else (reverse-search (reverse (rest lst)) target)]))

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], more than 4 years of experience and around 400 students in the past. ; sum-of-divisors: nat → nat (define (sum-of-divisors n) (foldr + 0 (filter (lambda (y) (zero? (remainder n y))) (build-list n (lambda (x) (add1 x)))))) ; grow-duplicates: (listof X) → (listof X) (define (grow-duplicates lst) (cond [(empty? lst) empty] [(= 1 (length lst)) empty] [(empty? (filter (lambda (x) (equal? x (first lst))) (rest lst))) (grow-duplicates (rest lst))] [else (append (grow-duplicates (rest lst)) (list (first lst)) (grow-duplicates (rest lst)))])) ; mystery-sort: (listof X)[nonempty] → (listof X)[nonempty] ; The elements of type X must be comparable with < and > (define (mystery-sort 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 list-of-lists next-list) (cond [(empty? lst0) (reverse (cons (reverse next-list) list-of-lists))] [(> (first lst0) (first next-list)) (partition (rest lst0) list-of-lists (cons (first lst0) next-list))] [else (partition (rest lst0) (cons (reverse next-list) list-of-lists) (list (first lst0)))]))

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], 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] [( 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 (right-angled, 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, right-angled

NOT FOR COMMERICAL USE, 请其他 tutor 自重不要使用我的资料,后果自负

CS115/116/2**/3** Private Tutor Service, Please contact Eagle Diao, Email: [email protected], 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 non-negative 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 more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF