unit 6: collections #2: lists, stacks,...

32
1 AP Computer Science Unit 6: Collections #2: Lists, Stacks, Queues Topics: I. Lists II. Stacks III. Queues IV. Prefix/Infix/Postfix notation Materials: I. Hein ch. 1.3 II. Dale, Joyce, & Weems ch 4.2 III. Dale, Joyce, & Weems ch 4.3 IV. Stack exercises V. Lisp programming overview (ACSL) VI. Prefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications IX. Infix to Prefix Specifications X. Postfix Evaluation Specifications XI. Word Palindrome Specifications XII. Stack and queue interfaces

Upload: trannguyet

Post on 19-Mar-2018

226 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

1

AP Computer Science

Unit 6: Collections #2: Lists, Stacks, Queues

Topics:

I. Lists II. Stacks III. Queues IV. Prefix/Infix/Postfix notation

Materials:

I. Hein ch. 1.3 II. Dale, Joyce, & Weems ch 4.2 III. Dale, Joyce, & Weems ch 4.3 IV. Stack exercises V. Lisp programming overview (ACSL) VI. Prefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications IX. Infix to Prefix Specifications X. Postfix Evaluation Specifications XI. Word Palindrome Specifications XII. Stack and queue interfaces

Page 2: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

2

Page 3: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

3

Page 4: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

4

Page 5: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

5

Page 6: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

6

Page 7: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

7

Page 8: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

8

Page 9: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

9

Page 10: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

10

Page 11: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

11

Page 12: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

12

Page 13: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

13

Stack Exercises

1. The statements push(p, q) and pop(p, q) handle two parallel stacks. The push puts p on the top of one stack and the q on the top of the second stack. The pop command does a pop of the first stack and puts the value into p, and a pop of the second stack and puts the value into q. For example, push(4, 6) push (2, 5) pop(a, b) pop(c, d) would result in a=2, b=5, c=4, d=6. Consider the following operations on an initially empty stack: push(40, 10) push(35, 3) push(12, 20) pop(a, b) pop(a, b) push(10, 23) What would be the next item removed from the “first” stack? 2. Trace the following pseudo-code: Stack s1; while (! End of input) { op = Get input; If (op is numeral) S1.push (op); Else { A = s1.pop(); B = s1.pop(); C = A op B; S1.push(C); } } Output s1.peek(); What will be the final value output if the input is: 3 4 + 5 4 + *

Page 14: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

14

LISP Programming LISP is one of the simplest computer languages in terms of syntax and semantics, and also one of the most powerful. It was developed in the mid-1950’s by John McCarthy at M.I.T. as a “LISt Processing language”. Today, it is used for virtually all Artificial Intelligence programs and is the environment of choice for applications which require a powerful interactive working environment. LISP presents a very different way to think about programming from the “algorithmic” languages, such as BASIC, Fortran and Pascal. As its name implies, the basis of LISP is a list. One constructs a list by enumerating elements inside a pair of parentheses. For example, here is a list with four elements (the second element is also a list):

(23 (this is easy) hello 821) The elements in the list, which are not lists, are called “atoms.” For example, the atoms in the list above are: 23, this, hello, 821, easy, and is. Everything in LISP is either an atom or a list (but not both). The only exception is “NIL,” which is both an atom and a list. It can also be written as “()” – a pair of parentheses with nothing inside. All statements in LISP are function calls with the following syntax: (function arg1 arg2 arg3 … argn). To evaluate a LISP statement, each of the arguments (possibly functions themselves) are evaluated, and then the function is invoked with the arguments. For example, (MULT (ADD 2 3) (ADD 1 4 2)) has a value of 35, since (ADD 2 3) has a value of 5, (ADD 1 4 2) has a value of 7, and (MULT 5 7) has a value of 35. Some functions have an arbitrary number of arguments; others require a fixed number. All statements return a value, which is either an atom or a list. We may assign values to variables using the function SET. For example, the statement (SET ’test ’6) would have a value of a 6, and (more importantly, however) would also cause the atom “test” to be bound to the atom “6”. The quote in front of the arguments indicates that the arguments should not be evaluated before the function is invoked. The quote in front of numbers is optional. Observe the following examples:

Statement Value Comment (SET ’a ( MULT 2 3)) 6 a is an atom with a vaue of 6 (SET ’a ’(MULT 2 3)) (MULT 2 3) a is a list with 3 elements (SET ’b ’a) a b is an atom with a value of the

character a (SET ’c a) (MULT 2 3) c is a list with 3 elements (SET ’TEST (ADD 3 (MULT 2 5)))

13 test has a value of 13

(SETQ VOWELS ’(A E I O U))

(A E I O U) VOWELS is a list of 5 elements

(SETQ x (SETQ y ’same)) same both x and y are bound to value of “same”

(SETQ y ’diff) diff x is still “same” (SETQ x y) diff x is now “diff”

Page 15: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

15

The function SETQ is the same as SET, but it causes LISP to act as if the first argument was quoted. The function EVAL returns the value of its argument, after it has been evaluated. For example, (SETQ z ’(ADD 2 3)) has a value of the list (ADD 2 3); the function (EVAL ’z) has a value of (ADD 2 3); the function of (EVAL z) has a value of 5 (but the binding of the atom z has not changed). In this last example, you can think of z being “resolved” twice: once because it is an argument to a function and LISP evaluates all arguments to functions before the function is invoked, and once when the function EVAL is invoked to resolve arguments. The function ATOM can be used to tell whether an item is an atom or a list.

Statement Value Comment (SETQ X (ADD 45 8)) 53 X is now 53 (SETQ Y ’(ADD X 11)) (ADD X 11) Y is now a list (EVAL ’Y) (ADD X 11) (EVAL Y) 64 (ATOM 5) true (ATOM X) true (ATOM ’Y) true (ATOM Y) NIL (ATOM ’(8 7 6)) NIL The two most famous LISP functions are CAR and CDR (pronounced: could-er), named after registers of a now long-forgotten IBM machine on which LISP was first developed. The function (CAR x) returns the first item of the list x (and x must be a list or an error will occur); (CDR x) returns the list without its first element (again, x must be a list). The function CONS takes two arguments, of which the second must be a list. It returns a list which is composed by placing the first argument as the first element in the second argument’s list. The function REVERSE returns a list which is its arguments in reverse order. The following examples illustrate the use of CAR, CDR, and CONS:

Statement Value (REVERSE ’(8 7 6)) (6 7 8) (REVERSE ’(1 (2 3 4) 5 6)) (6 5 (2 3 4) 1) (CAR ’(This is a list)) This (CAR (CDR ’(This is a list))) is (SETQ x (CDR (CDR ’(a b c d)))) (c d) (CDR ’(This is a list )) (is a list) (CAR ’(hi)) hi (CDR ’(one)) NIL (CAR ’((1) (2 3) (4 5 6))) (1) (CONS 32 ’(22 12)) (32 22 12) (CONS ’first ’(last)) (first last) (CONS ’(one) ’(two three)) ((one) two three) (CDR (CAR ’((red white) blue))) (white) (CONS (CAR ’(red green blue)) (CDR ’(brown tan (red tan gold)

Page 16: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

16

gold))) (CAR ’hi) error (CAR ()) error (CAR ’(ADD 2 2)) ADD (CONS 78 NIL) (78) (CDR ’((red green) (blue white)) ((blue white)) (SETQ a ’(orange black)) (orange black) (ATOM (SETQ b (CONS ’red a))) NIL (ATOM b) NIL (ATOM (CAR b)) true (ATOM NIL) true (SETQ fruit ’(apple orange)) (apple orange) (SETQ more (CONS ’grape fruit)) (grape apple orange) (CDR (CDR (REVERSE more))) (grape) (SETQ colors ’(red green yellow)) (red green yellow) (SETQ area (MULT 2 3)) 6 (SETQ A (CONS area ’(CDR colors))) (6 CDR colors) (SETQ B (CONS ’area (CDR colors))) (area green yellow) (SETQ C (REVERSE colors)) (yellow green red) (CAR (CDR C)) green (CONS ’pink (CONS ’orange (CONS C NIL))) (pink orange (yellow green

red)) As you have probably deduced, the function ADD simply summed its arguments. We’ll also be using the following arithmetic functions:

FUNCTION RESULT (ADD x1 x2 …) sum of all arguments (MULT x1 x2 …) product of all arguments (SUB a b) a-b (DIV a b) a/b (SQUARE a) a*a (EXP a n) an (EQ a b) true if a and b are equal, NIL otherwise (POS a) true if a is positive, NIL otherwise (NEG a) true if a is negative, NIL otherwise

Page 17: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

17

Some examples of these functions are as follows:

STATEMENT VALUE (ADD (EXP 2 3) (SUB 4 1) (DIV 54 4)) 24.5 (SUB (MULT 3 2) (SUB 12 (ADD 2 2))) -2 (ADD (SQUARE 3) (SQUARE 4)) 25

LISP also allows us to create our own functions using the DEF function. For example, (DEF SECOND(parms) (CAR (CDR parms))) defines a new function called SECOND which operates on a single parameter named “parms”. SECOND will take the CDR of the parameter and then the CAR of that result. So, for example: (SECOND ’(a b c d e)) would first CDR the list (yielding (b c d e)) and then CAR the result. So the value would be the single character “b”. Consider the following program fragment: (SETQ X ’(a c s l)) (DEF WHAT(parms) (CONS parms (REVERSE (CDR parms)))) (DEF SECOND(parms) (CONS (CAR (CDR parms)) NIL)) The following chart illustrates the use of the user-defined functions WHAT and SECOND:

STATEMENT VALUE (WHAT X) ((a c s l) l s c) (SECOND X) (c) (SECOND (WHAT X)) (l) (WHAT (SECOND X)) ((c))

Questions in this round will typically present a line of LISP code or a short sequence of statements and ask what is the value of the (final) statement. References Hofstadter, Douglas R. “Metamagical Themas,” in Scientific American, February, 1983. Also, see the March and April, 1983 columns for a more detailed look. These articles can also be found in Hofstadter’s delightful book, Metamagical Themas published by Basic Books (1985). Charniak, Eugene and Drew McDermott. An Introduction to Artificial Intelligence, Addison-Welsley (1985).

Page 18: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

18

Sample Problems

Evaluate: (CDR ’((2 (3))(4 (5 6) 7)))

The CDR function takes the first element of its parameter (which is assumed to be a list) and returns the modified list. The first element of the list: ((2 (3))(4 (5 6) 7)) is (2 (3)), and the list without this element is ((4 (5 6 ) 7)).

Consider the following program fragment: (SETQ X ’(RI VA FL CA TX)) (CAR (CDR (REVERSE X))) What is the value of the CAR expression?

The first statement binds variable X to the list (RI VA FL CA TX). The REVERSE of this list is the list (TX CA FL VA RI). whose CDR is (CA FL VA RI) The CAR of this list is just the atom “CA” (without the quotes).

Given the function definitions for HY and FY as follows: (DEF HY(PARMS) (REVERSE (CDR PARMS))) (DEF FY(PARMS) (CAR (HY (CDR PARMS)))) What is the value of the following? (FY ’(DO RE (MI FA) SO))

To evaluate (FY ’(DO RE (MI FA) SO)), we must first evaluate (CAR (HY (CDR ’(DO RE (MI FA) SO)))) Thus, HY is invoked with PARMS= ’(RE (MI FA) SO), and we evaluate (REVERSE (CDR ’(RE (MI FA) SO) )) This has a value of (SO (MI FA) ) which is returned to FY. FY now takes the CAR of this.

Evaluate the following expression. (EXP (MULT 2 (SUB 5 (DIV (ADD 5 3 4) 2)) 3) 3)

(EXP (MULT 2 (SUB 5 (DIV (ADD 5 3 4) 2)) 3) 3) (EXP (MULT 2 (SUB 5 (DIV 12 2)) 3) 3) (EXP (MULT 2 (SUB 5 6) 3) 3) (EXP (MULT 2-1 3) 3) (EXP –6 3) -216

Page 19: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

19

Prefix/Infix/Postfix Notation

One commonly writes mathematical expressions, such as DCBA+

−in infix notation: A-

B/(C+D). In this example, one must first evaluate C+D (call the result X), then B/X (call the result Y), and finally A-Y. The order of evaluation is not simply “go from left to right, evaluating on the fly.” Rather, evaluation is dependent on the precedence of the operators and the location of parentheses. Two alternative formats, prefix and postfix, have been developed to make evaluation more mechanical (and hence, solvable by a simple computer program). Prefix notation places each operator before its operands, and postfix places each operator after its operands. The example above becomes –A/B+CD in prefix notation, and ABCD+/- in postfix notation. In all notations, the relative order of the operands is the same. A simple algorithm for converting from infix to prefix (postfix) is as follows: (i) Fully parenthesize the infix expression. It should now consist solely of “terms”: a binary operator sandwiched between two operands. (ii) Write down the operands in the same order that they appear in the infix expression. (iii) Look at each term in the infix expression in the order that one would evaluate them, i.e., inner most parenthesis to outer most and left to right among terms of the same depth. (iv) For each term, write down the operand before (after) the operators. The following sequence of steps illustrates converting X=(A*B-C/D)↑E from infix to postfix: (X=(((A*B)-(C/D))↑E)) XABCDE XAB*CDE XAB*CD/E XAB*CD/-E XAB*CD/-E↑ XAB*CD/-E↑= This equation has a prefix value of =X↑-*AB/CDE. A quick check for determining whether a conversion is correct is to convert the result back into the original format. The area of computer science that uses prefix and postfix notation (also known as “Polish” and “Reverse Polish” notation for the Polish logician Jan Lukasiewicz) most frequently is compiler design. Typically, expressions (as well as statements) are translated into an intermediate representation, known as a “syntax tree,” which is equivalent to either prefix or postfix notation. The intermediate representation can then be easily executed. References Tenenbaum, Aaron M. and Moshe J. Augenstein. Data Structures Using Pascal, Prentice-Hall (1981), pp.76-95. Tremblay, Jean-Paul and Richard Bunt. Introduction to Computer Science, McGraw-Hill (1979), pp. 456-478.

Page 20: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

20

Sample Problems Translate the following infix expression into postfix.

BA

DCBA

+

+− 21

)(

The expression converts as follows: (A-BC/)+D)1/2AB+/ (ABC/-D+)1/2AB+/ ABC/-D+12/↑AB+/ It is wrong to simplify the 1/2 to .5 or to “sqrt”.

Given A=4, B=14 and C=2, evaluate the following prefix expression: * / - + A B C * A C B

Convert to infix: →* / - + A B C * A C B →* / -(A+B) C(A*C) B →* /((A+B) – C)(A*C) B →*(((A+B) – C) / (A*C)) B →((((A+B) – C) / A*C)) * B

→ B

CACBA *)

*( −+

Substitute and simplify:

2814*)2*4

2144( =−+

Evaluate the following prefix expression, when A=10, B=2, C=12 and D=2. + / ↑ - A B 2 ↑ / - C D / A B 3 / + AC B

Take the original prefix expression, + / ↑ - A B 2 ↑ / - C D / A B 3 / + AC B and make passes, each time putting as many binary operators as possible into place: + / ↑(A-B)2 ↑ /(C-D)(A/B) 3 /(A+C) B + /(A-B)2 ↑((C-D)/(A/B)) 3((A+C)/B) +((A-B)2/((C-D)/(A/B))3)((A+C)/B) B

CA

BADCBA +

+

−3

2

/

)(

This evaluates to 19.

Page 21: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

21

AP Computer Science

List Challenge Questions In the programming language “Lisp,” the function “CDR” returns the tail of a list (a sublist) and the function “CAR” returns the head of a list (item). 1. Evaluate: (CDR (CAR (CDR (CDR’ (2 (3 1) (4 5 (2 3 )) (6 1 (8 2) ) ) ) ) ) ) 2. Evaluate the following expression:

(CDR (CDR (CAR (CDR '(2 ((3 (4 5) 6) 7)))))) 3. Evaluate the following expression:

(ADD 1 (MULT 2 (SUB 3 (DIV 3 2)) 1))

4. Evaluate the following postfix expression. All numbers are single digits.

2 4 6 + * 5 / 3 2 ↑ 4 2 − * +

5. Convert the following prefix expression into a postfix expression.

+ − * A ↑ B C / B A * C + / A B C

Page 22: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

22

Project #6: Polygon* *Note that this project is a revision of the previous version. You must implement the project using a “Stack” object in order to get credit. Specifications: A polygon consists of several vertices (points) connected by lines. Create a program that allows the user to draw polygons as well as store and load them to/from a file. Use arrays and a mouse listener to keep track of the user’s mouse clicks. Beginning with a blank screen, each time the mouse is clicked, a new point is added to the polygon and it is redrawn. If the user clicks the “remove” button, the most recent point is removed from the list and the polygon is redrawn. If the user clicks on the “Save” button, the entire list is stored in a file called “polygon.txt,” where the file format is as follows: the first line of the file will be the number of vertices in the polygon and each line afterwards stores one (x,y) vertex pair as “world coordinates,” between the values -1.0 and +1.0. The program should handle a polygon up to 25 vertices.

Design: It will be helpful if you plan out your window with some declared constants to indicate where your buttons are located. For example: int REMOVEX = 25; int REMOVEY = 25; int REMOVEWIDTH= 70;

Page 23: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

23

int BUTTONHEIGHT=30; int CLEARX = 330; int CLEARY = 25; Implementation: It is required that you implement this program using two Stack objects, for the x values, and one for the y-values. As far as the “Stack” class is concerned, use the model(s) that we discussed in class. The member functions your structure should have are those included in the StackInterface: public void push (Object Item) /* Takes a parameter of any data type and inserts it into the top end of the Stack. If the Stack consists of strings, an example call to the function may be: MyStack.push(MyString); */ public Object pop() /* This function effectively deletes one item from the top of the Stack. Be sure that the data item is returned to the client code. If the Stack consists of strings, an example function call may be: MyString = MyStack.pop(); */ public boolean isEmpty() /* This Boolean-returning method will return true if there are no items in the Stack, otherwise false. */ public boolean isFull() /* This Boolean-returning method will return true if there are the maximum number of items in the Stack, otherwise false. */ public Object peek() /* This method returns the top without deleting it. */ In order to traverse the stack, you may not add any new methods! Instead, you must use either an additional (temporary) stack, or use recursion! You also must create a new class that extends the SSAWindow class. The methods you must implement include: public void mousePressed(int x, int y) // this is an over-ridden method—you may not alter the above method signature void removePoint() void addVertex(int x, int y) void drawAll() boolean clearButtonPressed(int x, int y) boolean removeButtonPressed(int x, int y)

Page 24: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

24

boolean saveButtonPressed(int x, int y) boolean loadButtonPressed(int x, int y) int worldToScreenX(double x) int worldToScreenY(double y) double screenToWorldX(int x) double screenToWorldY(int y) To draw the polygon you may use a series of lines or you may use the Polygon class. The SSAWindow class includes a drawPolygon method that will aid you in this. Testing: Be sure that your program gives appropriate messages (to the console) for “stack overflow” and “stack underflow.” Do not allow the user to add more than 25 points. Consider the following question: What advantages and disadvantages are met when limiting access to a collection?

Page 25: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

25

AP Computer Science

Programming Assignment #6: Infix to Prefix

Specifications: In this project, you will use stacks to convert “infix” notation expressions into “prefix” notation expressions. For instance, the expression: 2 + (4 – 3) * 6 is an infix expression. Its equivalent prefix expression would be: + 2 * - 4 3 6. The input will be in an input file, the name of which is entered at run-time. Each line of which contains a different infix expression. The first line of the file can contain the number of expressions. Each expression will contain the following characters: the mathematical operators “+”, “-“, “/”, “*”, the parentheses “(“, “)”, and single digit integer numbers. A space will separate each character. The following could be a possible data file: 3 2 + (4 – 3) * 6 8 / 4 – 2 * 5 3 + 4 * (2 * 2) – (9 / 3) The output will go to a file called “prefix.txt”. Each line will be the equivalent infix expression of the input file, followed by the evaluation of that expression. For the input file listed here, the output file would be: + 2 * - 4 3 = 8 - / 8 4 * 2 5 = -8 + 3 - * 4 * 2 2 / 9 3 = 16 Design As far as the “Stack” class is concerned, use the model(s) that we discussed in class. The member functions your structure should have are those included in the StackInterface: public void push (Object Item) /* Takes a parameter of any data type and inserts it into the top end of the Stack. If the Stack consists of strings, an example call to the function may be: MyStack.push(MyString); */ public Object pop() /* This function effectively deletes one item from the top of the Stack. Be sure that the data item is returned to the client code. If the Stack consists of strings, an example function call may be: MyString = MyStack.pop(); */ public boolean isEmpty() /* This Boolean-returning method will return true if there are no items in the Stack, otherwise false. */

Page 26: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

26

public boolean isFull() /* This Boolean-returning method will return true if there are the maximum number of items in the Stack, otherwise false. */ public Object peek() /* This method returns the top without deleting it. */ In order to traverse the stack, you may not add any new methods! Instead, you must use either an additional (temporary) stack, or use recursion! Implementation: The following represents an algorithm for using the stacks for converting infix to prefix: Algorithm ConvertInfixtoPrefix Purpose: Convert an infix expression into a prefix expression. Begin // Create operand and operator stacks as empty stacks. Create OperandStack Create OperatorStack // While input expression still remains, read and process the next token. while( not an empty input expression ) read next token from the input expression // Test if token is an operand or operator if ( token is an operand ) // Push operand onto the operand stack. OperandStack.Push (token) endif // If it is a left parentheses or operator of higher precedence than the last, or the stack is empty, else if ( token is '(' or OperatorStack.IsEmpty() or OperatorHierarchy(token) > OperatorHierarchy(OperatorStack.Top()) ) // push it to the operator stack OperatorStack.Push ( token ) endif else if( token is ')' ) // Continue to pop operator and operand stacks, building // prefix expressions until left parentheses is found. // Each prefix expression is push back onto the operand // stack as either a left or right operand for the next operator. while( OperatorStack.peek() not equal '(' ) OperatorStack.Pop(operator) OperandStack.Pop(RightOperand) OperandStack.Pop(LeftOperand) operand = operator + LeftOperand + RightOperand OperandStack.Push(operand) endwhile

Page 27: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

27

// Pop the left parentheses from the operator stack. OperatorStack.Pop(operator) endif else if( operator hierarchy of token is less than or equal to hierarchy of top of the operator stack ) // Continue to pop operator and operand stack, building prefix // expressions until the stack is empty or until an operator at // the top of the operator stack has a lower hierarchy than that // of the token. while( !OperatorStack.IsEmpty() and OperatorHierarchy(token) lessThen Or Equal to OperatorHierarchy(OperatorStack.Top()) ) OperatorStack.Pop(operator) OperandStack.Pop(RightOperand) OperandStack.Pop(LeftOperand) operand = operator + LeftOperand + RightOperand OperandStack.Push(operand) endwhile // Push the lower precedence operator onto the stack OperatorStack.Push(token) endif endwhile // If the stack is not empty, continue to pop operator and operand stacks building // prefix expressions until the operator stack is empty. while( !OperatorStack.IsEmpty() ) OperatorStack.Pop(operator) OperandStack.Pop(RightOperand) OperandStack.Pop(LeftOperand) operand = operator + LeftOperand + RightOperand OperandStack.Push(operand) endwhile // Save the prefix expression at the top of the operand stack followed by popping // the operand stack. print OperandStack.Top() OperandStack.Pop() End Testing and Debugging: Be sure that your program handles all the appropriate exception situations, such as undoing too many moves (popping from an empty stack). Be sure that your program gives appropriate messages (to the console) for “stack overflow” and “stack underflow.” Consider the following question: What advantages and disadvantages are met when limiting access to a collection?

Page 28: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

28

AP Computer Science

Programming Assignment No. 6: Postfix Arithmetic

Specifications: Most arithmetic that we do is done in “infix” notation, meaning that we place our operator between the two operands: “8 + 4” evaluates to 12. In a complex expression, however, we need to evaluate our result based on a system of precedence. The post-fix notation of arithmetic works like this: we place our two operands first and the operator last. For example, “8 4 +” evaluates to 12. Using post-fix helps to eliminate the need for precedence rules, as operations are always done with the most recent set of operands. The following expression: 3 6 8 + 4 * - is equivalent to writing 3 – (6 + 8) * 4. Here’s how it works. When operands (numbers) are encountered, they are pushed onto a stack. When an operator is encountered, it pops off the most recent two things placed on the stack, uses the operator to evaluate them, and then pushes the result back onto the stack. Hence, in the above example, the following could be the input file: 3 6 8 + 4 * - Here’s what the output file should be: 3 is pushed onto the stack 6 is pushed onto the stack 8 is pushed onto the stack +: 8 is popped 6 is popped 14 is pushed onto the stack 4 is pushed onto the stack *: 4 is popped 14 is popped 56 is pushed onto the stack -: 56 is popped 3 is popped -53 is pushed onto the stack Final contents of stack: -53 Design As far as the “Stack” class is concerned, use the model(s) that we discussed in class. The member functions your structure should have are those included in the StackInterface: public void push (Object Item)

Page 29: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

29

/* Takes a parameter of any data type and inserts it into the top end of the Stack. If the Stack consists of strings, an example call to the function may be: MyStack.push(MyString); */ public Object pop() /* This function effectively deletes one item from the top of the Stack. Be sure that the data item is returned to the client code. If the Stack consists of strings, an example function call may be: MyString = MyStack.pop(); */ public boolean isEmpty() /* This Boolean-returning method will return true if there are no items in the Stack, otherwise false. */ public boolean isFull() /* This Boolean-returning method will return true if there are the maximum number of items in the Stack, otherwise false. */ public Object peek() /* This method returns the top without deleting it. */ In order to traverse the stack, you may not add any new methods! Instead, you must use either an additional (temporary) stack, or use recursion! Testing and Debugging Be sure that your program handles all the appropriate exception situations, such as undoing too many moves (popping from an empty stack). Be sure that your program gives appropriate messages (to the console) for “stack overflow” and “stack underflow.” Consider the following question: What advantages and disadvantages are met when limiting access to a collection?

Page 30: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

30

AP Computer Science

Programming Assignment No. 6: Word Palindromes

Specifications: As you may recall, a palindrome is a word that is spelled the same both forwards and backwards, such as “radar,” “rotor,” or a phrase such as “rise to vote, sir!” A word palindrome is a palindrome based not on individual letters, but on words. For instance, “Never say never,” or “Fall leaves after leaves fall” are both word palindromes. For this project, you are to write a word palindrome detector using both a stack and a queue together. Your input will come from a file whose name will be determined at run time. The file will contain an indeterminate number of lines, each of which contains a sentence which may or may not be a word palindrome. The first line of the file may contain the number of lines. A few sample input lines could be as follows: 5

Fall leaves after leaves fall. Escher, drawing hands, drew hands drawing Escher. I’m not a palindrome.

Blessed are they that believe that they are blessed. Get, you pest! You get! Your output will go to a file called “palindrome.out.” This file will contain an echo of each input line followed by a message indicating whether it was a word palindrome or not. For instance, for the input file given above, the output file would be something like the following:

Fall leaves after leaves fall. – IS a word palindrome. Escher, drawing hands, drew hands drawing Escher. – IS a word palindrome. I’m not a palindrome. – Is NOT a word palindrome. Blessed are they that believe that they are blessed. – IS a word palindrome. Get, you pest! You get! – IS a word palindrome.

Design: A requirement of this program is to design a solution that makes use of both a stack and a queue. You will not receive credit for the assignment unless your solution utilizes both! The queue should include the following methods: public interface QueueInterface { public void enQueue (Object Item); /* Takes a parameter of any data type and inserts it onto the end

of the Queue. If the Queue consists of Strings, an example call to the function may be: myQueue.enQueue(myString); */

public Object deQueue (); /* This function effectively deletes one item from the front of

the Queue. If the Queue consists of Strings, an example call to

Page 31: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

31

the function may be: System.out.println(myQueue.deQueue()); */ public boolean isEmpty(); /* This Boolean-returning function will return true if there are

no items in the Queue, otherwise false. */ public Object peekFront(); /* Returns the front item without removing it. */ } Implementation: Because queues are linear, they can be implemented as either arrays or circular arrays. You may use either of these approaches, but be sure that your queue does not leave any non-accessible locations. Essentially, be sure that you shift items when appropriate. Testing and Debugging: Be sure that your queue works in all possible situations. In particular, test for stack and queue underflow / overflow. Be sure that your program gives appropriate messages (to the console) for “stack/queue overflow” and “stack/queue underflow.” Consider the following question: What advantages and disadvantages are met when limiting access to a collection?

Page 32: Unit 6: Collections #2: Lists, Stacks, Queuescs.shadysideacademy.org/ap/studenthandoutstacks2017.pdfPrefix/Infix/Postfix notation (ACSL) VII. Challenge Questions VIII. Polygon specifications

32

/* Stack Interface Updated: 11/12/04 AP Computer Science All objects of type Stack must implement the following methods. */ public interface StackInterface { public boolean isEmpty(); public boolean isFull(); public void push(Object x); // new item 'x' is added to the "top" of the stack public Object pop(); // item at the top of the stack is removed and returned public Object peek(); // item at the top is returned, but not removed } public interface QueueInterface { public void enQueue (Object Item); /* Takes a parameter of any data type and inserts it onto the end

of the Queue. If the Queue consists of Strings, an example call to the function may be: myQueue.enQueue(myString); */

public Object deQueue (); /* This function effectively deletes one item from the front of

the Queue. If the Queue consists of Strings, an example call to the function may be: System.out.println(myQueue.deQueue()); */

public boolean isEmpty(); /* This Boolean-returning function will return true if there are

no items in the Queue, otherwise false. */

public boolean isFull(); /* This Boolean-returning function will return true if there are

no free spaces in the Queue, otherwise false. */ public Object peekFront(); /* Returns the front item without removing it. */ }