Run Code  | Code Wall  | Users  | Misc  | Feedback  | About  | Login  | Theme  | Privacy 

Polyrmophism


            
                
            
 run  | edit  | history  | help 0

Sample exam (not much was done to make this look nice) Solutions are in white, or you can change the solution style. 1. Ask the user for an integer. Then write a for loop in python that asks for that many doubles. Lastly, output the arrays values divided by 2, using integer division, on the same line separated with a space. (pulled form actual exam) Example usages: Cnt: 4 Num: 1.5 Num: 2 Num: 4 Num: 4.5 0.0 1.0 2.0 2.0 Sample solution: x = [0] *5 n = int(input("Cnt: ")) for i in range(0,n): y = float(input("Num: ")) x[i] = y // 2

for i in range(0, n): print(x[i], end = " ")

  1. Write a python class that called Pumpkin. It must have the first letter capitalized. Pumpkin has the following: • A constructor that takes a optional radius. The default radius is 15. • A method called grow() that will increase the radius by 2%. • A override str() function that returns “Pumpkin: radius X” where x is the current radius 2pt per line, 1.5 for syntax, 0.5 for purpose

example solution class Pumpkin: def __init__(self, r = 15): self.radius = r

def grow( self ):
    self.radius *= 1.02

def __str__(self):
    return "Pumkin: radius " + str(self.radius)
  1. How does a generator compare to an iterator? (1-2 sentences) A generator can run forever while an iterator will stop at the end of its collection

  2. Consider the following pseudocode, assuming nested subroutines and static scope. What does this program print? Separate the numbers with one space. (nearly pulled from exam) g : integer

func B(a : integer) x : integer func A(n : integer) g = n func R(m : integer) print x x = x / 2 // integer division if x > 1 R(m + 1) else A(m) //back in B() x = a * a R(1) //back in main() B(3) print g

________(9 4 2 3) Print 9, x = 9, m = 1, x = 4 Print 4, x = 4, m = 2, x = 2 Print 2, x = 2, m = 3,

  1. Consider the following pseudocode (I’ve used very similar problems in exams) x = 1 y = 2 func add() x = x + y func second( m : method() ) local x = 2 m() func first() local y = 3 second(add) first() print x

a. What does this program print if the language uses static scoping? (3) b. What does it print if the language uses dynamic scoping with deep binding (closure-based dynamic scoping)?________ (4) deep binding uses the current state (closure) when the method is made an argument is made. At the second (add), this means the local y and outer x. This is halfway better static and dynamic with shallow binding

c. What does it print if the language uses dynamic scoping with shallow binding (standard dynamic scoping)?________ (1) shallow binding evaluates at its location of use. This is the more standard dynamic scoping. This means at x = x + y, it sees the local x and local y first, and uses them. This also means it set the local x! by the time we back out, the outer x remains the same: 1

  1. Python allow easy implementation of the iterator pattern since functions are first class objects. What are the two main parts of the pattern if we do not have first class functions? The interface to place the functions, and setting up the main class to accept and call and concrete instance of the interface.

  2. What does yield do in Python? It pauses the function and optionally returns a value. When the function is called again, it restarts right after the yield.

  3. How does an iterator aid in encapsulation? (1-2 sentences) It protects the collection from direct access

  4. Name one solid principle the iterator pattern aids in keeping, and why? (pulled from exam) I is the most obvious. It is the primary reason for the iterator pattern O is also easy claim as it stops people from having to open up the collection L is another large one and it forces to treat sub element the same way

  5. Select all of the following that should use a strategy pattern rather than inheritance or the visitor pattern: (pulled from exam)

A plant blooms only in a given season which can change with the hemisphere. It blooming method is dependent on the specific flower object.

All plants grow.

A car engine processes fuel a certain way, and this can depend on the vehicle and can change depending on how the vehicle is driven.

You have several dogs all with their own size The first and third options. Plants growing all have the same function and the function remains the same for all instances of the class, so inheritance works. Dog size should be an instance variable.

Blooming changes with the individual plant, so inheritance doesn’t work. Fuel process also changes with the individual vehicle, so inheritances doesn’t work.

  1. What is Type Compatibility? (essentially pulled form exam) A type rule that deals with which types a construct will accept or not

  2. Explain how data types would be used/handled in a language that is both weakly typed and dynamically typed (2-3 sentences). Give an example variable declaration. (pulled from exam) This is close to LISP which I’ve referenced in class. You would not need to explicitly declare the datatype since it would be determined by the value assigned to it. However, since it is weakly typed, this also means we can cast without explicit notation since datatypes are fluid. Since it is dynamic, it is almost guaranteed to have garbage collection as well. Example usage: x = 2 x = 'c' +2 will result in 'e' or the ACSII value of 'e'

  3. Why do many modern languages include properties rather than only traditional member variables? Ease of use. Adding a setter/getter is assumed in everything that has to be accessed outside the class, so this simplifies use.

  4. Write the regular expression for 0 or more a’s followed by 1 or 2 bs. a*b{1,2}

  5. Diagram the following problem Description Suppose you are writing a system to keep score for a game of bowling. Here is an example of a bowling score card:

There are 10 frames. In each frame the bowler rolls two balls. Each box represents one frame. The number of pins knocked down for a rolls is put on the top of the box, as shown above. The scores accumulate. A strike is when the bowler knows down all of the pins with one roll. In that case there is no second roll. A spare is when the bowler knocks down all of the pins with the second roll. Here is how a frame is scored: If neither a strike or spare is rolled, the frame score is the previous frame score plus the number of pins knocked down in this frame. In frame 2 above, the score is the previous frame's 5 plus 4 plus 5 = 14. If a spare is thrown, the number of pins in the next roll is added as a bonus to the frame score. In frame 3 a spare has been rolled. The score is 14 (previous frame) plus 10 (this frame) plus 5, the next roll = 29. If a strike is thrown, the number of pins in the next two rolls is added as a bonus to the frame score. In frame 5 a strike this thrown. The score is 49 (previous frame) plus 10 (this frame) plus 0 (next roll) plus 1 (next roll after that) = 60. The 10th frame is special in that you can roll one extra ball if you get a strike in the 10th frame. Required Functionality: You must be able to roll and retrieve the score. Reset the picture to make it show

Explanation: Note the prev/next links on the frame. If we do that, it is easy to compute the score.

Alternative The 10th frame is special. That needs to be accomodated in some way. I took a "roll" as a thing and made a class for it. That works well since a frame may have 0 to 3 rolls. But, another reasonable approach would be to make the roll an attribute:

This is a reasonable solution, but it will be harder to tell a partially rolled frame. Do we set roll1 and roll2 to zero initially? Or maybe -1 to mean an invalid value? That's why I prefer the first version.

  by  xyoussi_youssr@lttmobile.com, 2 months ago


www.google.com

  by  xyoussi_youssr@lttmobile.com, 2 months ago


encapsulation - In object-oriented programming, encapsulation is an attribute of object design. It means that all of the object's data is contained and hidden in the object and access to it is restricted to members of that class.

polymorphism - In programming languages and type theory, polymorphism is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types.

orthogonality - operations change just one thing without affecting others.

  by  xyoussi_youssr@lttmobile.com, 2 months ago


S (Single responsibility) - In programming, the Single Responsibility Principle states that every module or class should have responsibility over a single part of the functionality provided by the software.

O (Open-closed) - In programming, the open/closed principle states that software entities (classes, modules, functions, etc.) should be open for extensions, but closed for modification.

L (Liskov substitution) - In programming, the Liskov substitution principle states that if S is a subtype of T, then objects of type T may be replaced (or substituted) with objects of type S. This can be formulated mathematically as Let ϕ(x) be a property provable about objects x of type T. Then ϕ(y) should be true for objects y of type S, where S is a subtype of T. More generally it states that objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

I (Interface segregation) - In programming, the interface segregation principle states that no client should be forced to depend on methods it does not use. Put more simply: Do not add additional functionality to an existing interface by adding new methods. Instead, create a new interface and let your class implement multiple interfaces if needed.

D (Dependency inversion) - In programming, the dependency inversion principle is a way to decouple software modules. This principle states that High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.

  by  xyoussi_youssr@lttmobile.com, 2 months ago


Strategy pattern

Its job is to swap out individual pieces of functionality

Its main competing patterns are general hierarchy and the visitor pattern

Strategy vs Visitor

Visitor Does an operation Can change over time Is type specific Can interact with multiple classes

Strategy Does an operation Can change over time Type of class generally unknown Affects only one class

Why Strategy

-Aids in the solid principles of O and I -Helps with code reuse -Better allows future behavior changes

Strategy pattern requirements

You know the type (or at least the parent with a known behavior) There is an operation The operation belongs to the instance (not an operation on the instance)

  by  xyoussi_youssr@lttmobile.com, 2 months ago


Iterator pattern

1 it points to a location 2. it moves that pointer 3. it returns an object at its current location 4. somehow signals when there are no more elements

why iterators

  1. for-each loops
  2. allows the collection storage implementaiton to vary without affecting the class's use
  3. allow more control over how and what is accessed (safety and encapsulation)
  4. SOLID principles it helps: I and D

Generator and iterators

main difference is one makes the elements as it goes (generator), and the other pulls them from a collection (iterator)

  by  xyoussi_youssr@lttmobile.com, 2 months ago


Regex

[] a set of characters "[a-m]" \ signals a special sequence (can also be used to escape special characters) "\d" . Any character (except newline character) "he..o" ^ Starts with "^hello" $ Ends with "world$" * Zero or more occurrences "aix*" + one or more occurrences "aix+" {} Exactly the specified number of occurrences "al{2}" | Either or "falls|stays" () Capture and group

Special sets

[arn] a, r, or n [a-n] a through n [^arn] any character not a, r, or n

\d digit \w a-z, digits, and underscore \b specificed chars are at beginning or end of word

any five letter string starting with a and ending with s - ^a...s$

  by  xyoussi_youssr@lttmobile.com, 2 months ago


Binding - 7 places

1) language design - * -> mult. - ^ -> exponent 2) implementation - what are base types 3) program time - name - classes 4) compile time - static - global - constants 5) link time - add in libraries 6) load time - where program is in memory 7) run time - everything else

first class objects - paramater, assign, argument, returns second class objects - passed in - constants third class objects - cant be passed in - keywords/syntax

  by  xyoussi_youssr@lttmobile.com, 2 months ago




Please log in to post a comment.
as
ONP