Programming Concepts Midterm #2
0. (0 points) NAME___________________________________ PERIOD _______
1. (5 points; each subproblem 1 point apiece) What will the outputs be from the following pieces of code? If you think that the code will produce an error, write ERROR.
(Hint: Show your work. It not only makes it easier for the teacher to understand what you are doing, but it might help you follow what you are doing, too!)
A. (accumulate word (every (lambda (x) (last (bl (bl x)))) '(giraffe wallaby parrot bobcat cockateel))) farce B. (keep (lambda (wd) (>= (count wd) 4)) '(the quick brown fox jumps over the lazy dog)) (quick brown jumps over lazy) C. ((repeated (repeated bf 2) 3) 'abcdefghij) ghij D. ((lambda (a b c) (- b (+ a c))) 1 4 9) -6 E. ((repeated (lambda (x) (* 5 x)) 2) 3) 75
2. (5 points) (Arya Haghighi) Mr. O'Connell is grading one of his impossible tests again. :-( Apparently everyone did horribly and no one received an A. He wants to know the average score on the test.
Write the function average that takes a sentence of numbers as its input and returns the average of the numbers. You may assume that the sentence contains at least one number.
> (average '(67 49 80 55 71 68)) 65 > (average '(1 2 3 4 5 6 7 8 9 10)) 5.5
(define (average sent)
(/ (accumulate + sent) (count sent)))
3. (5 points) (Patrick Ruehl) Mr. Dunbar has a habit of pushing biology teachers off of a cliff. The height of a cliff is the square of the number of years a teacher has taught at Gunn. Given a list of teachers, where the first letter represents the subject (B=Biology, C=Chemistry, P=Physics) and the rest is the number of years the teacher has been at Gunn, write the dunbar function which produces a sentence of the heights of all of the cliffs Mr. Dunbar uses.
> (dunbar '(P7 B6 B2 C4 B5 C2)) ; only the biology teacher years are squared (36 4 25) (define (square x) (* x x)) (define (dunbar sent) (every square (every bf (keep (lambda (wd) (equal? (first wd) 'B)) sent))))
4. (5 points in two parts) (Based on a problem by Christine Chen) The function backwards flips a sentence and every word in the sentence:
> (backwards '(!drofnats taeb lac og)) (go cal beat stanford!) > (backwards '(emoctuo dna noitatcepxe sesufnoc inamriv veejar)) (rajeev virmani confuses expectation and outcome)
4A. (2 points) First, fill in the blanks to write reverse, which reverses a single word.
(define (reverse wd)
(________________________________ (lambda (ltr1 ltr2) (________________________________)) wd))) (define (reverse wd)
(accumulate (lambda (ltr1 ltr2) (word ltr2 ltr1)) wd))
4B. (3 points) Now write backwards. You may assume that your answer to 4A was correct.
(define (backwards sent) (accumulate (lambda (wd1 wd2) (se wd2 wd1)) (every reverse sent)))