Exam 1

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What are the strings s, c, and r after the following statements are executed? s = 'attrition'.upper() c = 't'.upper() r = s.replace(c, c.lower()) For your answer, provide the string, with no surrounding quotes. s: c: r:

s: ATTRITION c: T r: AttRItION

What is the sequence of numbers generated by the invoking the following range? range(25, 5, -4) As before, enter your answer as a series of integers, separated by commas.

25,21,17,13,9

What is the bash command for making file lab2.py executable by the user? Be sure you have used the correct filename before grading your answer.

chmod u+x lab2.py

What are the strings s and t after the following statements are exectuted? s = 'Sober' t = s.upper() For your answer, provide the string, with no surrounding quotes. s: t:

s: Sober t: SOBER

Given a string s, that is at least 3 characters long, which of the following is the same as s[0:-1]?

s[:len(s)-1]

Coordinate transformation

is a well-studied component of computer graphics

Given the following function defintion: def say_hello(name): print('Hello ' + name + '!') How would you invoke the function so that 'Hello Reese!' is displayed?

say_hello('Reese')

Magnetic or optical media are generally used for:

secondary memory

Identifiers in Python may not contain

spaces

Aliasing is the situation when

two different variables refer to the same object in memory

In modern Python, an int that grows very large

uses more memory

Main memory is______ , which means that the information in memory is lost when power is turned off.

volatile

Although not covered in our textbook, augmented assignment is a relatively simple concept. See Lessons → Chapter 2 → Augmented Assignment. After the following code executes, what are the values for w, x, y and z? w, x, y, z = 3, 4, 5, 24 a, b, c, d = 11, 8, 4, 4 w += a x -= b y *= c z /= d

w: 14 x: -4 y: 20 z: 6

How would you create a 200x200 graphics window titled MyWindow?

win = GraphWin('MyWindow')

What command would set the coordinates of win to go from (0,0) in the lower-left corner to (10,10) in the upper-right?

win.setCoords(0, 0, 10, 10)

Suppose you want to create a square graphics window and draw lines to divide it into four equal-sized quadrants. Fill in the missing line in this code: win=GraphWin('Four Square', size, size) # missing line here Line(Point(0,1),Point(2,1)).draw(win) Line(Point(1,0),Point(2,0)).draw(win)

win.setCoords(0,0,2,2)

Suppose that the variable x currently has the value 20. What statement would cause the value of x to become 25?

x = x + 5

After executing the following code, what are the values of x, y, and z? x = 2 y = 7 z = 11 x, y, z = y, z, x Reference: Textbook §2.5.3, Simultaneous Assignment

x:7 y:11 z:2

What are the smallest (closest to −∞) and largest (closest to +∞) values of y printed? ex: for index in range(6): y = -5 * index + 9 print(y)

Smallest: -16 Largest: 9

What is the value of result after the following code executes? adjective = 'fast' animal = 'walrus' separator = "+" result = adjective + separator + animal

fast+walrus

What is the string fauna after the following statements are executed? animals = ["dog", "fox", "rat", "cat", "pig", "elk"] fauna = '#'.join(animals) fauna:

fauna: dog#fox#rat#cat#pig#elk

The Python numeric type for representing numbers containing fractional values is

float

Given the following function definition: def fun(): print("Fun World") What statement would you use to invoke this function?

fun()

Python is an example of a(n):

high-level programming language

Which of the following are Python keywords?

import class break nonlocal

What Python statement allows the math library to be used in a program?

import math

What is the value of index after the following statements are executed? animals = ["dog", "fox", "cat", "elk", "pig", "rat"] index = '%%'.join(animals).find('o') For your answer, provide the string, with no surrounding quotes. index:

index: 1

Which of the following commands would be used to open a file called "foobar.dat" so that its contents could be read into memory?

infile = open("foobar.dat","r")

The Python built-in function for getting string input interactively from the user is

input

Which of the following is not a category of object methods? Reference: Textbook §4.4 mutator

instance variable

The Python numeric type that is best for representing positive and negative whole numbers is

int

What is the result of evaluating this expression: "{0}.{1:02}".format(13,8)?

"13.08"

What character is used to indicate the beginning of a comment in Python?

#

The average of 2 numbers is the sum of the two numbers divided by 2. Enter a valid expression which computes the average of two variables a and b.

(a+b)/2

Suppose the script snake1.py is in the current working directory, is executable, and has an appropriate 'shebang' line. What is the bash command for executing this script?

./snake1.py

Suppose variable 'x' has the value 0.586. What is the floating-point value of the following Python expression? 3.9 * x * (1 - x)

.946

Invoking range(stop) yields a sequence of integers, from 0 ... stop - 1. Suppose variable x has the value 4. What sequence is produced by the expression range(x + 3)? Enter your answer as a sequence of integers, separated by spaces.

0 1 2 3 4 5 6

What is the output of the following loop? ex multiplier = 8 for i in range(3): print( (multiplier * i) + 1 )

1 9 17

Which of the following are valid string literals?

1. "my script" 2. 'my script' 3. "Reese's script" 4. "42"

1. Write an expression using the format method to right-justify the int variable a in a field 8 characters wide, padded on the left zeroes. 2. Write an expression using the format method to left-justify the int variable a in a field 8 characters wide, padded on the right with the pound-sign character (#). 3. Write an expression using the format method to center the int variable a in a field 8 characters wide, padded with asterisks (*).

1. '{:08}'.format(a) 2. '{:#<8}'.format(a) 3.'{:*^8}'.format(a)

1.Write an expression using the format method to right-justify the int variable z in a field 6 characters wide. 2.Write an expression using the format method to left-justify the int variable z in a field 6 characters wide. 3.Write an expression using the format method to center the int variable z in a field 6 characters wide.

1. '{:6}'.format(z) 2. '{:<6}'.format(z) 3. '{:^6}'.format(z)

Let's look again at the integer division (//) and remainder (%) operators. What if the dividend (top number) and/or divisor (bottom number) is negative? It turns out that the remainder is always computed to be the same sign as the divisor, and the integer division satisfies the rule a = (a//b) × b + a % b 1. -16 // 3= ? 2. -16 % 3= ? 3. 16 // -3= ? 4. 16 % -3= ? 5. -16 // -3=? 6. -16 % -3= ?

1. -16 // 3= -6 2. -16 % 3= 2 3. 16 // -3= -6 4. 16 % -3= -2 5. -16 // -3= 5 6. -16 % -3= -1

Evaluate the following expressions. Enter the result in the corresponding box (or the letter x if the evaluating the expression produces an error). If your answer is a float value, your answer should be accurate to at least 3 decimal places. In the corresponding dropdown box, indicate whether the result is an integer, float, or error condition. Note: Assume the math library is available, via an import math statement. 1. abs(5 - 14 // 3) ** 3 2. math.sqrt(7 - 8) + 8 * 5 3. math.sqrt(abs(7 - 8)) + 8 * 5

1. 1 integer 2. x error 3. 41.0 float

Which of the following expressions result in a float value of 123?

1. 123.0 2. float(int('123')) 3. 123 / 1 4. float('123')

Let's look at the integer division (//) and remainder (%) operators. Compute the value of the following expressions. Your answers should be integers for the first two answers. Your answers must be floating point for the second two answers (since the use of 3.0 rather than 3 forces the answer to be floating point). 1. 13 // 3= ? 2. 13 % 3= ? 3. 11 // 3.0= ? 4. 11 % 3.0= ?

1. 13 // 3= 4 2. 13 % 3= 1 3. 11 // 3.0= 3.0 4. 11 % 3.0= 2.0

Evaluate the following expressions. Enter the result in the corresponding box (or the letter x if the evaluating the expression produces an error). If your answer is a float value, your answer should be accurate to at least 3 decimal places. In the corresponding dropdown box, indicate whether the result is an integer, float, or error condition. 1. 5.0 / 10.0 + 3.5 * 2 2. 18 % 4 + 7 // 5 3. 10 ** 4 + 4 / (2 * 10 - 20)

1. 7.5 float 2. 3 integer 3. x error

Identify the type of assignment in the following lines of code: 1. r *= w 2. r, y = 9 , 11 3. r = w * z

1. Augmented Assignment r *= w 2. Simultaneous Assignment r, y = 9 , 11 3. Simple Assignment r = w * z

The 3 steps the CPU performs when it processes a machine instruction are called:

1. Fetch 2. Decode 3. Execute

Use the Python interpreter to find the output from the following Python statements. Please omit the newline that Python will generate at the end of each line of output. 1. print("Goodbye, world!") 2. print("Goodbye", "world!") 3. print(2) 4. print(2.0) 5. print(2 + 8) 6. print(2.0+8.0) 7. print("2"+"8") 8. print("2 + 8 =", 2 + 8 ) 9. print(2 * 8) 10. print(2 ** 8)

1. Goodbye, world! 2. Goodbye world! 3. 2 4. 2.0 5.10 6. 10.0 7. 28 8. 2 + 8 = 10 9. 16 10. 256

Select the corresponding character (or character sequences) that have the following mean in the bash command line interface. 1. Home directory 2. Current directory 3. Parent directory 4. Path separator 5. Wildcard for filenames

1. Home directory ~ 2. Current directory . 3. Parent directory .. 4. Path separator / 5. Wildcard for filenames *

Your best friend, Reese Sintacks, has been hired by NASA to create a launch simulator for the upcoming human mission to Mars. Reese wrote a function countdown() which is supposed to generate the following output: 3 ... 2 ... 1 ... 0 ... Blastoff! However, the code is not working properly. Suggest changes Reese should make so that the countdown() method will product the desired output: def countdown() for i in range(3) print(3-i, '...') print('Blastoff!)

1. add a single quote after the exclamation point in Blastoff! 2.change the argument of the range function to 4 3.add a colon (:) at the end of the for statement 4.add a colon (:) at the end of the function definition

In the following Python function declaration def generate_message(name, message_type): what role do the the identifiers name and message_type play?

1. arguments 2. parameters

Which of the following are functions in the Python math library? Note: Table 3.2 in your textbook is only a partial listing of functions in the math library. Consult the online reference Python 3.3 Documentation for a complete listing.

1. hypot(x, y) 2. log10(x) 3. cos(x)

A(n) ________ analyzes and executes source code as necessary. A(n) ________ translates from source code written in high-level language to machine code.

1. interpreter 2. compiler

Which of the following are Python built-in functions ?

1. len() 2. int() 3. float() 4. range() 5. round()

Which of the following are listed as Trigonometric Functions in the Math library documentation?

1. math.atan(x) 2. math.acos(x) 3. math.cos(x) 4. math.asin(x)

Given a float value, we frequently want an int value near the float value. Depending on the situation, we may want the next higher or next lower integer, or we may want the closest integer. Note the use of the floor ⌊⌋ and ceiling ⌈⌉ symbols, which you may not have seen before. floor(x) = ⌊x⌋ is the largest integer ≤ x ceiling(x) = ⌈x⌉ is the smallest integer ≥ x. Ref: Wikipedia: Floor and ceiling functions We can also round off to the nearest integer, or truncate toward zero. Suppose x is 1.65. Use the Python interpreter (remembering to import the math library) for the following computations, which should help you understand how these functions work. 1. math.floor(x) 2. math.floor(-x) 3. math.ceil(x) 4. math.ceil(-x) 5. round(x) 6. round(-x) 7. math.trunc(x) 8. math.trunc(-x)

1. math.floor(x) 1 2. math.floor(-x) -2 3. math.ceil(x) 2 4. math.ceil(-x) -1 5. round(x) 2 6. round(-x) -2 7. math.trunc(x) 1 8. math.trunc(-x) -1

Which of the following are listed as constants in the Math library?

1. math.pi 2. math.e

Suppose p1 and p2 are Point objects. What expression(s) could compute the distance between these two points?

1. math.sqrt((p2.getX()-p1.getX())**2 + (p2.getY()-p1.getY())**2) 2. math.hypot( p2.getX()-p1.getX(), p2.getY()-p1.getY() )

Suppose that variable x has the value 591.8902588046464. What is the result of the following invocations of round()? 1. round(x) 2. round(x,2) 3. round(x,-1)

1. round(x) 592.0 2. round(x,2) 591.89 3. round(x,-1) 590.0

Given a string s, which of the following is/are the same as s?

1. s[:5] + s[5:] 2.s[:] 3. s[0:] 4. s[:len(s)]

Which of the following are legal identifiers?

1. spam4U 2. _3 3. spAm 4. spam 5. spam_and_eggs

Modern digital computers represent numbers

1. using a binary representation 2. using a sequence of bits 3. using only zeroes and ones ***= all of the above

Suppose day, month, and year are int variables containing the current day, month, and year numbers. Which of the following expressions would produce a properly formatted date in month/day/year format?

1."{0}/{1}/{2}".format(str(month),str(day),str(year)) 2."{0}/{1}/{2}".format(month,day,year) 3.str(month)+"/"+str(day)+"/"+str(year) ***= all of the above

Differences between compilers and interpreters:

1.a compiler is no longer needed after a program is translated 2.a compiler translates an entire program written in a high-level language into machine language

Given a Text object named myText, which statements would be combined to produce bold arial font, size 16 points?

1.myText.setStyle('bold') 2.myText.setSize(16) 3.myText.setFace('arial')

Suppose variable 'fahrenheit' has the value 10. What is the floating-point value of the following Python expression? 5 / 9 * (fahrenheit - 32)

10.0

How many times is the body of this loop executed? ex: for index in range(12): print(index * 3)

12

Previously, we worked invoked the range function with only 1 parameter. However, the range function accepts up to 3 parameters, so providing additional flexibility as to the sequence of numbers we can obtain. What is the sequence of numbers generated by the invoking the following range? range(3, 7) Enter your answer as a series of integers, separated by commas. For example, if your answer were the first 3 counting numbers, you would enter 1,2,3

3, 4, 5, 6

The number of distinct patterns that can be represented with 5 bits is

32 **look at page 68

What is the sequence of numbers generated by the invoking the following range? range(5, 13, 2) As before, enter your answer as a series of integers, separated by commas.

5,7,9,11

You are close to discovering the password of a cyberterrorist! The password characters are represented by the following sequence of ASCII decimal values. Decode the password using either an ASCII table or the Python built-in chr() function. 67 83 35 82 48 107 115

C 67 S 83 # 35 R 82 0 48 k 107 s 115

Which statement correctly draws a circle of radius 10 centered at (50,50) in the graphics window win?

Circle(Point(50,50), 10).draw(win)

Fill in the rgb color values for the following colors: brown orange dodgerblue

Color red green blue brown 165 42 42 orange 255 165 0 dodgerblue30 144 255

Because Python identifiers are not case-sensitive, a Python variable named myvar can be referenced using any of the following: myvar, MYVAR, MyVar, myVar.

False

If the following statement is executed, outfile = open('mydata.out', 'w') the program will crash if mydata.out already exists.

False

Programmers rarely define their own functions.

False

Programs no longer require modification after they are written and debugged.

False

Python keywords are good choices for Python identifiers (e.g., variable names or function names).

False

Python keywords comprise only lower-case letters.

False

The best way to write a program is to immediately write down some code, then debug it until it works.

False

The term GUI stands for

Graphical User Interface

Indicate the terms represented by the following acronyms

RAM — Random Access Memory CPU — Central Processing Unit DVD — Digital Versatile Disc USB — Universal Serial Bus

What class in the graphics.py module would be best for drawing a square?

Rectangle

What does the rgb stand for in the graphics function color_rgb?

Red Green Blue

ASCII is a standard for representing characters using numeric codes.

True

An algorithm can be written without using a programming language.

True

Expressions are built from literals, variables, and operators.

True

Hardware is the physical computer system; software contains the instructions used to control the hardware.

True

In Python "4" + "5" is "45".

True

In mathematics, x=x+1 is nonsense, since subtracting x from both sides means 0=?1 However, in Python as in most computer languages, x = x + 1 is a legal statement.

True

Instance variables are used to store data inside an object.

True

Modules, variables, and functions are named using identifiers. Ref: Textbook, §2.3.1, p. 31

True

Python identifiers must start with a letter or underscore.

True

The last character of a string s is at position len(s)-1.

True

The programming language Python is named after the British comedy troupe Monty Python's Flying Circus rather than the snake.

True

The readline() method for file objects returns all text up to and including the next newline character.

True

The split() method breaks a string into a list of substrings, and join() does the opposite.

True

Traditionally, the upper-left corner of a graphics window has coordinates (0,0).

True

Using the / operator to divide two numbers always results in a float value, even if the two numbers are int's.

True

A successor to ASCII that includes characters from nearly all written languages is

Unicode

What is the bash command for changing the working directory to its parent?

cd ..

What is the bash command for changing the working directory to /usr/bin ?

cd /usr/bin

What is the result of evaluating list(range(1,7,2))?

[1,3,5]

A statement is

a complete computer command

A step-by-step set of instructions for accomplishing some task is called a(n)

algorithm

Characterize the following line of Python script: x = x_0 + velocity * delta_t

assignment statement

What is the value of c after executing the following Python script? isogram = "artichokes" c = isogram[-6]

c

A method that creates a new instance of a class is called a(n)

constructor

Which of the following are Python keywords?

continue import while *look up keywords in the book

Which of the following are Python keywords?

continue as lambda

I usually begin a new Python script by copying an existing script that has some similarity to the script I want, then begin editing from there. Assume lab1.py exists in the current directory. What is the bash command for creating a copy of this script with the name lab2.py ? Be sure you have used the correct filenames before grading your answer.

cp lab1.py lab2.py

An object combines

data and operations

The area of an ellipse is given by A=πab where a and b are the semiminor and semimajor axes (see diagram). In the graphics.py module, ellipses are created using the less mathematically formal term oval. Create a function areaOfEllipse(ellipse), which calculates the area of an ellipse. The single parameter ellipse is an Oval object. As the documentation indicates, this ellipse (or oval) is represented by the bounding box determined by the two points P1 and P2. The math module is available, so you can use math.pi. P1 P2 a b

def areaOfEllipse(ellipse): p1, p2 = ellipse.getP1(), ellipse.getP2() a = ( p2.getY() - p1.getY() ) / 2 b = ( p2.getX() - p1.getX() ) / 2 return math.pi * a * b

Create a function areaOfRectangle(rectangle), which calculates the area of a rectangle. P1 P2 width height Hints: Use rectangle.getP1() and rectangle.getP2() to get the corners of the rectangle. Use getX() and getY() to get the x and y coordinates of P1 and P2. compute the width and height return width × height (which is the area of a rectangle)

def areaOfRectangle(rectangle): p1, p2 = rectangle.getP1(), rectangle.getP2() deltaX = p2.getX() - p1.getX() deltaY = p2.getY() - p1.getY() return deltaX * deltaY

Create a function buildSquare(center, side), where center is a Point object, and side is a float. Your function should return a Rectangle object that is a square centered at center, with side length side. side center side/2 side/2 Remember that a Rectangle is created from points at opposite corners, so you will need to first produce Point objects which correspond to the points indicated by magenta circles in the diagram, then use those points to create the desired Rectangle.

def buildSquare(center, side): half_side = side / 2 x, y = center.getX(), center.getY() p1 = Point(x - half_side, y - half_side) p2 = Point(x + half_side, y + half_side) return Rectangle(p1, p2)

Create a function buildTriangle(rectangle), where rectangle is a Rectangle object. Your function should return a Polygon object that is a triangle composed of the lower left 3 points of the triangle. You may assume that rectangle.getP1() returns the upper left point of the rectangle, and rectangle.getP2() returns the lower right point of the rectangle, as in the diagram. P1 P2 P3 To create a Polygon representing the green triangle, you will need P1, P2, and a third point P3 that you will need to create.

def buildTriangle(rectangle): p1 = rectangle.getP1() p2 = rectangle.getP2() p3 = Point( p1.getX(), p2.getY() ) return Polygon(p1, p2, p3)

In this category, you will be asked to define some simple functions, which require at most a few lines (often only 1 or 2 lines in the function body) to implement. Your code will have to follow very specific guidelines in order for the automatic grader to recognize it as correct. So that you will understand exactly what is expected, this first problem is a giveaway. I provide you with the code for the function ... all you have to do is cut-and-paste into the solution box. The area of a circle is given by the formula A=πr2 Write a function called circle_area which accepts a single parameter radius. Your function will return the area of a circle with the given radius. Simply cut-and-paste the following solution into the answer box: def circle_area(radius): return math.pi * radius ** 2 Behind the scenes, import math has already been executed, so you don't need to include any import statement to use the math library. def circle_area(radius): return math.pi * radius ** 2 You won $1100 !!! Number Representation Math Library Numeric Computation range() and round() Expressions Defining Functions

def circle_area(radius): return math.pi*radius ** 2

What is the bash command for removing child directory lab1 from the current directory? Be sure you have used the correct directory name before grading your answer.

rmdir lab1

Given a square, a circle circumscribes the square if all four of the corners of the square lie on the circle. Create a function circumscribingCircle(square), which accepts a single parameter square, which is a Rectangle object that is known to have equal length sides (and is thus a square). Your function should return a Circle object that is a circle circumscribing the square. r P1 P2 From the diagram, you should see that the circle you need to create has the same center as the square, and has a radius equal to 1/2 the diagonal of the square.

def circumscribingCircle(rectangle): side = abs( rectangle.getP2().getX() - rectangle.getP1().getX() ) radius = math.hypot( side/2, side/2 ) return Circle(rectangle.getCenter(), radius)

Create a function createText(textString, anchorPoint, family, size, style), which is a function that returns a Text object containing the string textString, centered at anchorPoint (a Point object). Assume the line from graphics import * has already been executed. Your function should call the appropriate methods on the text object (Textbook § 4.8.2, p. 111) so that the text object has the text content, anchor point, font face, point size, font style, and color indicated by the function parameters. For example, after instantiating the text object, set the font face with the statement text.setFace(family)

def createText(textString, anchorPoint, family, size, style): text = Text(anchorPoint, textString) text.setFace(family) text.setSize(size) text.setStyle(style) return text

We wish to calculate the distance between points (x1, y1) and (x2, y2). Using the Pythagorean theorem, distance=Δx2+Δy2−−−−−−−−−√ (x1,y1) Δx = x2 - x1 (x2,y2) Δy = y2 - y1 Write a function distance which accepts 4 parameters: x1, y1, x2, y2 (in that order). The function should return the distance between the points.

def distance(x1, y1, x2, y2): deltay = y2 - y1 deltax = x2 - x1 return math.hypot(deltax, deltay) # or, if you forgot about math.hypot # return math.sqrt(deltax ** 2 + deltay ** 2)

Create a function distanceBetweenCircles(circle1, circle2), which returns the closest approach distance between two circles circle1 and circle2. P1 P2 r1 r2 d We want to calculate the distance d in the diagram, which is the black line segment. The problem is easier than it may seem. Simply calculate the distance between the centers of the circles (we have already seen how to calculate the distance between two Point objects). Then subtract the radius of each circle (r1 and r2 in the diagram). You may assume the circles will not overlap.

def distanceBetweenCircles(circle1, circle2): center1, center2 = circle1.getCenter(), circle2.getCenter() deltaX = center2.getX() - center1.getX() deltaY = center2.getY() - center1.getY() centerDistance = math.hypot(deltaX, deltaY) return centerDistance - circle1.getRadius() - circle2.getRadius()

Given an arbitrary triangle with sides of length a, b, and c, Heron's Formula can be used to calculate the area of the triangle. First we take the intermediate step of calculating the semiperimeter (half of the perimeter) of the triangle: s=a+b+c2 Then the area of the triangle is given by A=s(s−a)(s−b)(s−c)−−−−−−−−−−−−−−−−−√ Write a Python function called herons(a,b,c) that accepts three parameters, the length of the 3 sides of a triangle, and returns the area of that triangle. Assume that the math library has already been imported, so you can use math.sqrt(x) to calculate a square root.

def herons(a,b,c): s=(a+b+c)/2 return math.sqrt(s*(s-a)*(s-b)*(s-c))

A Rectangle object is described by Point objects P1 and P2. These 2 points form a diagonal line segment (indicated with red dashes in diagram). Create a function oppositeDiagonal(rectangle) which returns a Line object. This line should have endpoints at the opposite 2 points of the rectangle (i.e., the line segment indicated with red dashes in the diagram).

def oppositeDiagonal(rectangle): p1 = rectangle.getP1() p2 = rectangle.getP2() p3 = Point( p1.getX(), p2.getY() ) p4 = Point( p2.getX(), p1.getY() ) return Line(p3, p4)

Create a function perimeterOfTriangle(p1, p2, p3), which returns the perimeter of the triangle formed by the 3 Point objects, p1, p2, p3,

def perimeterOfTriangle(p1, p2, p3): a = math.hypot(p1.getX() - p2.getX(), p1.getY() - p2.getY() ) b = math.hypot(p2.getX() - p3.getX(), p2.getY() - p3.getY() ) c = math.hypot(p3.getX() - p1.getX(), p3.getY() - p1.getY() ) return a + b + c

We wish to calculate the slope of a line which passes through points (x1, y1) and (x2, y2). (x1,y1) Δx = x2 - x1 (x2,y2) Δy = y2 - y1 slope = Δy / Δx Write a function slope which accepts 4 parameters: x1, y1, x2, y2 (in that order). The function should return the slope of the line.

def slope(x1, y1, x2, y2): deltay = y2 - y1 deltax = x2 - x1 return deltay / deltax

The volume of a sphere is given by the formula V=43πr3 Write a function called sphere_volume which accepts has a single parameter radius. Your function will return the volume of a sphere with the given radius. As before, import math has already been executed, so you don't need to include any import statement to use the math library.

def sphere_volume(radius): return 4 / 3 * math.pi * radius ** 3

In the following Python code def greeting(person): pass what does def mean?

define

A batch-oriented program is one that

does its input and output through files

What string results from evaluating the following expression? 'dog' * 4

dogdogdogdog

hat is the bash command for converting DOS-style line endings into Unix-style line endings?

dos2unix

What is the bash command for listing all files (including directories) in the current working directory?

ls

What is the bash command for creating a directory in the file system?

mkdir

A graphics display is composed of a grid of very small picture elements whose color can be controlled. These elements are called

pixels

The statement infile = open('myfile.dat', 'r') has already been executed. Which of the following program fragments will display the contents of the file exactly as in the file?

print(infile.read(), end='')

An algorithm is like a

recipe

What is the value of c after executing the following Python script? isogram = "introduces" c = isogram[2]

t

Write an expression that extracts a slice of string t which extends from the character at index 1 and ends with the character at index 7. For example if t were unpredictably your expression would return npredic

t[1:8]

Assume string t is at least 10 characters long. Use slices and concatenation to write an expression that concatenates the first 3 and last 4 letters of string t. For example if t were unpredictably your expression would return unpably

t[:3]+t[-4:]

From basic trignometry, there are 2 usual ways of measuring angles, in radians or degrees. Which of the following statements correctly uses a Math library function to convert x degrees into radians, storing the result in variable theta?

theta = math.radians(x)

One disadvantage of using binary floating point representations is that

they are often only approximations

The goal of the design phase of the software development process is

to create an algorithm that solves the problem

The goal of the specification phase of the software development process is

to determine what the program should do

What is the value of s after executing the following Python script? isogram = "noticeably" s = isogram[::-1]

ylbaeciton

The string "slots" that are filled in by the format method are marked by:

{ }


Kaugnay na mga set ng pag-aaral

Production of Goods and Services

View Set

CompTIA Network+ N10-008 Post-Assessment Quiz

View Set

Tenneesse New Affiliate 30 hour Program Missed questions

View Set