Reference no: EM133539193
Programming Fundamentals
Part A: Examples of "what will be output by the following code" and "correct the code (both syntax, logic and structure)" type questions.
Examples of this type of questions are provided below. Other examples can be found in the sample exam and in the weekly tutorial questions.
Question 1
What are the key distinctions among runtime, syntax, and semantic errors in programming?
Please review the 'word_match()' function provided. It accepts two parameters: 'words', which is a list of strings, and 'word', which is a string. The purpose of this function is to determine if the given 'word' exists in the list. If the word is found, the function returns its index; otherwise, it returns -1.
def word_match(words, word):
index = -1
for (i,item) in enumerate(words):
if item != word:
i = index
break
return i
(a) Does this function contain an error? If there is an error, could you identify the type of error and suggest how to rectify it?
(b) Rewrite the word_match() function, correcting any errors if they exist.
(c) Test the word_match() function by performing the following steps:
• Create a list words = ["Jim", "Adam", "Camaroon", "Flintof"].
• Call the word_match(words, "Camaroon") function and assign the return value to a variable named index.
• Print the value of the variable index.
(d) What test caseswould you employ to thoroughly test your word_match()function?
Question 2
This question tests your understanding of parameter passing in Python.Remember, in python parameter passing is "pass by object reference".
• Everything is an Object:In Python, everything is an object, whether it's a number, string, list, or a more complex data structure. Each object has a type and a value.
• Object Reference:When you create an object in Python (e.g., a list), what you get is a reference (or a memory address) to that object. Think of it as a label that points to the actual object in memory.
• Passing by Value (of References):When you pass an argument to a function in Python, you are passing the reference (memory address) to the object. However, this reference is passed by value, meaning a copy of the reference is passed to the function.
• Modifying the Object vs. Reassigning the Reference:Inside the function, you can modify the object that the reference points to (if the object is mutable), and these modifications are visible outside the function. However, if you reassign the reference to a new object, this reassignment is local to the function and doesn't affect the original reference in the caller.
Recall in python for:
• Immutable objects, the behaviour is like pass by value, since a new object is created each time, the value is changed.
• Mutable object the modifications to the objects (attributes) inside the function are visible outside the function, giving the appearance of "pass by reference."
(a) What is output by the following code?
def swap(a,b):
temp = a
a = b
b = temp
a = 10
b = 20
print("Before swap")
print("a: {}, b:{}".format(a,b))
swap(a,b)
print("After swap")
print("a: {}, b:{}".format(a,b))
(b) Explain why the swap method above does not achieve the required swap. (In the exam you would not be given so much of a hint - you would just be asked to explain the results.)
(c) Now we are going to pass a list to swap function. Lists are mutable objects. What is output by the following code?
def swap(lst):
temp = lst[0]
lst[0] = lst[1]
lst[1] = temp
a = 10
b = 20
lst = [a, b]
print("Before swap")
print("a: {}, b:{}".format(a,b))
swap(lst)
a = lst[0]
b = lst[1]
print("After swap")
print("a: {}, b:{}".format(a,b))
(d) Explain why the swap method above achieves the required swap?
Question 3
In Python the scope of an identifier is the region of program code in which the identifier can be used or accessed.
Three important scopes in python:
• Local scope
• Global scope
• Built-in scope
Local scope refers to variables or identifiers that are defined within a specific function. Each function creates its own isolated namespace, and any variable declared within that function will only be accessible within that function's scope.
Global scope refers to all the identifiers (variables, functions, classes, etc.) that are declared at the top level of the current module (i.e., outside any functions or classes). These identifiers are accessible throughout the entire module, including from within any functions or classes defined within that module.
Built-in scope is a predefined collection of names that includes various built-in functions, classes, and exceptions. These names are automatically available to use in any Python script or module without requiring any additional imports.Some examples of built-in functions are print(), str(), int(), and float().
Recall the python scope look up rules:
Local scope will always take precedence over the global scope, and the global scope always gets used in preference to the built-in scope.
Predict the output of the code below?
i = 6
f = 5.5
s = "Hello World!"
l = [1, 2, 3, 4]
t = (1, -1, 2, 5)
def update(i, f, s, l, t):
i = 20
f = -9.5
s = "Good bye!!"
l[1] = 5
t = (2, 2)
print("Inside Update function i: {}, f: {}, s: {}, l: {}, t: {}".format(i,f,s,l,t))
print("Before update function i: {}, f: {}, s: {}, l: {}, t: {}".format(i,f,s,l,t))
update(i, f, s, l, t)
print("After update function i: {}, f: {}, s: {}, l: {}, t: {}".format(i,f,s,l,t))
Question 4
What would be the output by the following program?
def function1(lst, index, item):
lst.insert(index, item)
def function2(lst, item):
lst.append(item)
def function3(lst):
dellst[-1]
lst = [5, 6, 7, 8]
#(a)
function1(lst, 2, 9)
print(lst)
#(b)
function2(lst, 10)
print(lst)
#(c)
function3(lst)
print(lst)
Question 5
(a) What will be output by the following code if the user enters 3 in response to the prompt for the year?
year = input("What year are you in? ");
if year == '1':
print("You are a freshman")
elif year == '2':
print("You are a sophomore")
elif year == '3':
print("You are a junior")
elif year == '4':
print("You are a senior")
else:
print("Invalid year")
Question 6
What will be output by the following code:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = len(matrix)
m = len(matrix[0])
for row in range(m):
for column in range(n):
print(matrix[row][column])
Part B Coding Questions
You may also be required to write pseudocode. It is advisable that you familiarize yourself with the pseudocode for major algorithms, including searching, sorting, list traversal, etc.
There are typical examples of coding questions in the sample exam and in your weekly tutorial exercises that you can use for practice.
Typical coding questions will include applications that require you to write code that includes the any combination of the following:
• Reading data from the user, performing calculations, and outputting the results in a specified format
• Writing a class and creating an object of the class and using it in a client method
• Using if-elif-else state
• Using loops - for and while loop for , tracking max/min, totals etc. in loops
• Using collections like list and tuples
• Catching exceptions, raising exceptions
• Reading and writing to files
• Working with different types of variables (like, str, int, float etc.)
It is essential that you are able to implement a class based on its specifications. Below is an example of a potential exam question in this regard:
Question 1
Make a class called Point with the following specifications:
Attributes (Instance variables):
• x: a float representing the x-coordinate of the point.
• y: a float representing the y-coordinate of the point.
Methods:
• __init__(self, x, y): Initializes a new instance of the Point class with the given x and y coordinates.
• distance(self, other): Calculates the distance between this point and another point specified by the other parameter.
• reflect_x(self): Returns a new Point instance that is a reflection of this point across the x-axis.
• slope_from_origin(self): Calculates the slope of the line joining the origin to this point.
• __eq__(self, other): Determines if this point is equal to another point specified by the other parameter.
• __str__(self): Returns a string representation of the point in the form of (x, y).
a) Make a list of five points with the coordinates (0, 1), (1, 3) ,(2, 5) ,(3, 7), (4, 9)?
b) Use for loop to print the coordinates of the points in the list using the __str__() method?
c) Determine slope_from_origin for the second point in the list?
d) Use the distance method to determine the distance between the first point and the last point in the list?
Part C: Examples of written/explain type questions
1. What are the essential components of a computer?
2. What is the function of Central Processing Unit in a Computer?
3. What is the function of main memory in a computer?
4. What is a program?
5. What are input and type converter functions in Python, and how do they contribute to the processing and manipulation of data within the language?
6. What is a "debugger" and why programmers use it?
7. What are special class methods in python? What is the purpose of the following special class methods:
a. __str__()
b. __eq__()
c. __lt__()
d. __gt__()
8. What languages use a more easily understood vocabulary with descriptive terms like "read", "write" or "add"?
9. What is the name of the software than translates high level language statements into machine code at once and generates an executable file?
10. What is source code?
11. If your code compiles and produces output when it runs does it necessarily mean it is correct? Explain.
12. Why do we use comments in our code? Are they executed?
13. What is the difference between mutable and immutable data types? Provide example of two immutable and one mutable data type in Python.
14. Evaluate the following numerical expressions in your head, then use the Python interpreter to check your results:
a. >>> 5 % 2
b. >>> 9 % 5
c. >>> 15 % 12
d. >>> 12 % 15
e. >>> 6 % 6
f. >>> 0 % 7
g. >>> 7 % 0
15. In a python program how would you determine if an integer was even or odd?
16. What is the purpose of the len() function in Python? If the list "my_list = [2, 3, 4, 5,7,8]" is given, what value will be returned by len(my_list)?
17. If n = 2 what will be the output of:
a. print(n%2 == 0 and n%3 == 0)
b. print(n%2 == 0 or n%3 == 0)
18. For each program segment, read the code, and write the output. Do not execute the programs on a computer. (You can check your answer by running the code on a computer after you have predicted the output, but not before.)
19. What is output by the following code?
x = 3
y = 2
print( x * y + 9 / 3 )
What is output by the following line of code?
print( ( 8 * 4 * 2 + 6 ) / 2 + 4 )
What is output from the following line of code?
print((1 / 4 + 2) * 4)
20. What is short circuit evaluation? Give an example.
21. Evaluate the following (the results will be either true or false) . Assume x is 100 and y is 150.
i. ((x >= 100) and (y <= 200))
ii. ((x < 100) and (y < 200))
iii. ((x < 100) or (y < 200))
iv. not((x < 100) or (y < 200))
22. What do these expressions evaluate to?
a) 3 == 3
b) 3 != 3
c) 3 >= 4
d) not (3 < 4)
23. What is the result of each of the following:
a. >>> "Python"[1]
b. >>> "Strings are sequences of characters."[5]
c. >>>len("wonderful")
d. >>> "Mystery"[:4]
e. >>> "p" in "Pineapple"
f. >>> "apple" in "Pineapple
g. >>> "pear" not in "Pineapple"
h. >>> "apple" > "pineapple"
i. >>> "pineapple" < "Peach"
24. What will be the output of following arithmetic expressions:
a. 2*5/2+5-10
b. (5-2)**2*6
c. (2+2-4)*1000/2
d. (6+6*6)**2**2
25. Predict the output of the following program in Python without running it.
this = ["I", "am", "not", "a", "crook"]
that = ["I", "am", "not", "a", "crook"]
print("Test 1: {0}".format(this is that))
that = this
print("Test 2: {0}".format(this is that))
Part A:
Question 1
a) You will be required to make some changes to the adventure game code. The code for the adventure game is available on the unit website (in the same area as this worksheet).
• Download the code.
• Read and become familiar with the code.
• Compare the code to the UML diagram (in the lecture slides)
b) Run the code and test the code thoroughly (e.g. with valid commands, with invalid commands, with a move command that does not have a room, with a move command with a non-existent room, with a move command where you try to enter a room not connected to the current room etc.)
For invalid commands, include strategically placed spaces, just a space, nothing (hit return), incorrect commands, valid commands but with uppercase present ...
c) You are to:
i. add some additional rooms to the world and have them connect to other rooms in the world. How will you do that? (Discuss your answers in class.)
ii. Extend the game so that the rooms can contain a list of items that a player may wish to collect in future iterations of the game. Modify the code so that when you enter a room the list of items are also displayed. (An example of the output with this extension is shown below.)
Output (after adding treasure to the rooms)
Welcome to a very boring adventure game.
Available commands are help, move,quit; move requires a room name with a single space as separator.
You are in a bar.
The treasuresthat you can seeare:diamond necklace, gold nugget
The rooms that you can enter are: sauna gym spa pool.
What changes will be required to do this? (Discuss your answers in class.)
d) Modify the data so that you add at least two new rooms to the world with appropriate connections. Make sure that the rooms can be reached via at least one of the existing rooms. Test the modified program and make sure that you can visit your new rooms.
e) Modify the code to include treasure in the rooms as described earlier. Add some treasure to some of your rooms and test your extended code.
Part B: Tutorial Question
Question 1
a) A common programming practice is to provide all classes with getters and setters for all attributes. Does this constitute good design practice? Explain your answer.
b) Critique the design of the Adventure game in terms of cohesion and coupling. What would the impact be of introducing a command class into the design?
Question 2
Consider the following description for a consoleapplication for an airline that hasn't kept up with the times:
To check flights, the user enters a check command which is read by a command loop. The system then prompts for the details of the proposed flight (return/single, date, from, to, number of seats, ...). The system then checks the proposed flight details against its list of scheduled flights and displays any scheduled flights that match the proposed flight. The user can then exit or conduct a new search.
From the above description,
1. Identify candidate objects for the application
2. Specify how those objects will interact / collaborate to achieve the specified behaviour
3. Identify candidate attributes and methods for each object
4. Generate a class diagram for the application