联系方式

  • QQ:99515681
  • 邮箱:99515681@qq.com
  • 工作时间:8:00-21:00
  • 微信:codinghelp

您当前位置:首页 >> Python编程Python编程

日期:2018-06-28 04:20


Page 1 of 26

SAMPLE EXAMINATION PAPER

Information Technologies

EXAMINATION

Semester 1 - Main, 2018

INFO1110/COMP9001 Introduction to Programming

EXAM WRITING TIME: 2 hours

READING TIME: 10 minutes

EXAM CONDITIONS:

This is a RESTRICTED OPEN book examination - specified materials permitted

During reading time - writing is not permitted at all

MATERIALS PERMITTED IN THE EXAM VENUE:

(No electronic aids are permitted e.g. laptops, phones)

Calculator - non-programmable

One A4 sheet of handwritten and/or typed notes double sided

MATERIALS TO BE SUPPLIED TO STUDENTS:

None

INSTRUCTIONS TO STUDENTS:

Please tick the box to confirm that your examination paper is complete.

Room Number ________

Seat Number ________

Student Number |__|__|__|__|__|__|__|__|__|

ANONYMOUSLY MARKED

(Please do not write your name on this exam paper)

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 2 of 26

Question 1 (20 marks): /20

1.a: ( /2)

Mark the following statements true or false:

(a) python includes a compiler

(b) a programming function can accept no input and produce an output

(c) the code f(x+1, y) = 1 will return the correct value of x and y in order to

produce the value 1

(d) There are only three data types in Python3: string, int and float

1.b: ( /2)

Mark the following statements true or false:

(a) when running a python program from the command line, the arguments include

the command python

(b) if x is assigned to an object, and y is assigned to x, then there are two copies of

the object in memory

(c) only a number can be used to represent an error

(d) an array is a contiguous region of memory for the same data type

1.c: ( /1)

What will the following code produce as output?

1 print("1 + 2 + 3" + str(1 + 2 + 3) + str(1) + str(2) + str(3) )

1.d: ( /1)

What does the execution of the operation f > 47 achieve?

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 3 of 26

1.e: ( /2)

Describe a unary operator.

1.f: ( /2)

What are the values of a and t after the following lines have been executed?

1 a=4

2 t = a+1

3 a -= a // 3

1.g: ( /2)

Given the statement x = some string, where variable some string is a string type, what are

two essential operations performed with Python3 operation float(x)?

1.h: ( /2)

What are the values of b and t after the following lines have been executed?

1 b = -3

2 t = -(+(b))

3 b += b / 3

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 4 of 26

1.i: ( /3)

Given an input from the user, Write down all the combinations of output this code will make.

1 x = input()

2 if x == "A":

3 print("A")

4 if x != "A":

5 print("B")

6

7 if x != "A":

8 print("C")

9 if x != "C":

10 print("D")

11

12 print("END")

1.j: ( /4)

The following is the XOR truth table

A B XOR

00 0

01 1

10 1

11 0

Write a function to return the correct value based on inputs a and b

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 5 of 26

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 6 of 26

Question 2 (15 marks): /15

The following code are the contents of the file subloco.py:

1 if 7 != sys.arg then

2 finish()

3

4 if int(sys.argv[0]) << int(sys.argv[5]) then

5

6 if (int(sys.argv1 - int(sys.argv3) > max(-1, sys.argv1) then

7 print("Unable to confirm") # quit

8

9 elseif float(sys.argv6 * int(sys.argv4)) > sys.argv1 then

10 print("We can make this happen") # process this data

11 comp1 = [ sys.argv6, sys.argv4 ]

12 comp2 = [ sys.argv1, sys.argv3 ]

13 if len(comp1[0]) > len(comp2[0]) then

14 diff = len(comp1[0]) - len(comp2[0])

15 for j in range(len(comp2) - len(comp1)) do

16 foreach in range(diff) do

17 print=(i + "th best is: " + str(comp2))

18 output result

A command was entered via the shell in the same directory as the file. The output is shown below:

$ python subloco.py

File "subloco.py", line 1

if 7 != sys.arg then

ˆ

SyntaxError: invalid syntax

9 marks - Part 1 - Describe all syntax errors of the entire program based on Python3 programming

language compiler (not only what is shown above).

6 marks - Part 2 - Describe three significant logic errors without knowing what the program is

supposed to do, or how it is supposed to work. Explain why these are logic errors and how they

cannot be confused with the programmers intention.

For both parts, you may use annotations on the code, or references to line numbers of the code to

help describe errors. Giving only the line number, or annotating an region of code does not form a

description.

Provide your answers on the next page clearly marking which are syntax and which are logic errors.

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 7 of 26

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 8 of 26

Question 3 (20 marks): /20

3.a: ( /10)

There is a game involving three balls. When each ball has been sunk, the game ends.

Write two functions, game() and sink().

Function sink() has two outputs: 1) print information to standard out and; 2) return an integer. It

accepts two input values, the name of the ball, and an initial position of the ball x. Each time the ball

changes position, a message will be printed to console. For example, when name is ”Ball 1” and x is

3

Ball 1 is 3

Function game() returns nothing. It accepts three input values, the names of each ball. It will

produce three random numbers for each of the balls initial position in the range [100,

100]. The

function will run the sink function for each ball and will ends when all balls 1, 2 and 3 have been

sunk (see math notation below).

import random

random.randint(a, b) method of random.Random instance

Return random integer in range [a, b], including both end points.

game(name1, name2, name3) = sink(name1, r1) ^ sink(name2, r2) ^ sink(name3, r3)

sink(name, x) =

8

><

>:

1, if x = 10

sink(name, x + 1), if x < 10

sink(name, x

1), otherwise

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 9 of 26

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 10 of 26

3.b: ( /10)

Write a program that would calculate the sum of all integer numbers of a file and print the sum to

standard output. The input to the program is a file provided as the first argument to the program.

Within the file, there is expected to be one number per line with no spaces. However, there may be

numbers which have a e instead of a 3. Only integer values contribute to the sum and lines that are

not integers are discarded. If there are no values in the file, then zero is the sum.

Example of running the program:

$ python total.py numbers_file

If there is no file name provided your program will behave as follows:

$ python total.py

No argument

If the file does not exist your program will behave as follows:

$ python total.py file.txt

Cannot open file

numbers file:

9

1

4

$ python total.py numbers_file

14

numbers file:

3

e3

4

$ python total.py numbers_file

7

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 11 of 26

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 12 of 26

Question 4 (15 marks): /15

4.a: ( /7)

Write a function prototype and a function body to perform the following:

The function returns the index of the last value in a list that satisfies the criteria:

3x + 4y>z

vi

where vi is the ith value in the list. The input to the function is a list of integers, and three integer

values x, y, and z. -1 is returned if 1) If no such value exists, or 2) the input list is empty, or 3) the

types of x, y, z or any of the values vi are not integer types.

Restrictions: In your function you may only use while loops, if statements, function len(),

keywords elif, else, return, break, continue, def, None and any arithmetic or boolean

comparison operators. Do not use a for loop, marks will be deducted. You cannot use slices, cannot

use the in keyword.

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 13 of 26

4.b: ( /8)

Write the function get png().

get png() returns a list of strings that contain the suffix ".png" where it is case insensitive. The

function accepts a list of strings as input. If there are no results, an empty list is returned. If the input

is not a list type, an empty list is returned. Hint: use isinstance(obj, class)

The suffix match is not case-sensitive. Examples of valid suffix: ".png", ".PNG", ".pNg",

".Png", ".PnG", ···

Restrictions: In your function you may only use while loops, if statements, function len(),

keywords elif, else, return, break, continue, def, None and any arithmetic or boolean

comparison operators. str comparator == and str method lower(). Do not use a for loop,

marks will be deducted. You cannot use slices, cannot use str comparator other than ==, cannot use

string methods other than len () and lower(), cannot use the in keyword.

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 14 of 26

Question 5 (20 marks): /20

You are tasked to complete the methods of the following class ShoeRepair.

A shoe repair shop serves customers who bring one or two shoes to be repaired. Each customer has

an identifier that is assumed unique. They give their right and/or left shoe to the shop along with their

identifier.

The shop records the customers status in a dictionary for each shoe. The possible status values can be

”repair”, ”restore”, or ”ready”.

The shoes in the shop are stored in two queues: the work queue and the completed queue. The work

queue represents shoes that are waiting to be, or are currently being repaired. The completed queue

are the shoes that have been repaired and are awaiting collection.

If one shoe has exactly one issue, it is a repair job and takes 1 unit of time. If a shoe has at least two

issues, it is a restore job and takes n units of time, where n is the number of issues with the shoe.

When a shoe is repaired or restored two events take place: 1) they are moved from the work queue to

the completed queue and; 2) the customer status of the shoe is updated.

Shoes with zero issues are immediately moved to the completed queue. A customer can collect their

shoe(s) if they are all ready.

A shoe object has multiple issues recorded as True or False values

class Shoe:

'''A datatype describing a single Shoe and it's issues as boolean values.'''

def __init__(self, heel, under_sole, inner_sole, eyelets, recolour,

buff_n_polish):

self.issues = {

"heel":heel,

"under_sole":under_sole,

"inner_sole":inner_sole,

"eyelets":eyelets,

"recolour":recolour,

"buff_n_polish":buff_n_polish

}

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 15 of 26

class ShoeRepair:

''' Define the datatype of a Shoe repair shop. '''

def __init__(self):

self.status = {}

self.work_queue = []

self.completed_queue = []

def count_issues(self, shoe):

# implement this

def is_restore(self, shoe):

# implement this

def add_shoes(self, identifier, shoe_right, shoe_left):

if 0 == count_issues(shoe_right):

self.completed_queue.append(shoe_right)

self.status[identifier + "_right"] = "ready"

elif shoe_right != None:

job_type = "repair"

if is_restore(shoe_right):

job_type = "restore"

self.status[identifier+"_right"] = job_type

self.work_queue.append(shoe_right)

if 0 == count_issues(shoe_left):

self.completed_queue.append(shoe_left)

self.status[identifier + "_left"] = "ready"

elif shoe_left != None:

job_type = "repair"

if is_restore(shoe_left):

job_type = "restore"

self.status[identifier+"_left"] = job_type

self.work_queue.append(shoe_left)

def repair_shoe(self, identifier, shoe):

# implement this

def restore_shoe(self, identifier, shoe):

# implement this

def collect_shoes(self, identifier_list):

# implement this

4 marks Part 1 - Implement the method count issues(self, shoe)

”’Returns an integer representing the number of boolean values that are True in the given shoe

objects issues data structure. If None is given, -1 is returned”’

2 marks Part 2 - Implement the method is restore(self, shoe)

”’Returns a boolean value. True is returned if the shoe object is a ”restore” job, False otherwise.”’

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 16 of 26

4 marks Part 3 - Implement the method repair shoe(self, identifier, shoe)

”’repair a single shoe. On success removes the shoe from the work queue and adds the shoe to the

completed queue. Updates the status based on the identifier that includes ” left” or ” right” to signify

which shoe it is. If there is no shoe in the status, nothing is done.”’

4 marks Part 4 - Implement the method restore shoe(self, identifier, shoe)

”’restore a single shoe. removes the shoe from the work queue and adds the shoe to the completed

queue. Updates the status based on the identifier. If there is no shoe in the status, nothing is done.”’

6 marks Part 5 - Implement the method collect shoes(self, identifier list)

”’Checks the status of each identifier in the identifier list and if they are all ”ready”, then all shoe(s)

belonging to that identifier list are removed from the completed queue and returned as a list of Shoe

objects. Otherwise, if at least one shoe from this identifier list that is NOT ready, then None is

returned.”’

Restrictions: You cannot change the way the data is being stored by method add shoes(). You

are permitted to add any helper methods/functions you require to solve any of the above. There are

no Python language restrictions.

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 17 of 26

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 18 of 26

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 19 of 26

Question 6 (10 marks): /10

A new numbers data type is defined. This has three different iterators that can be chosen at runtime.

You are only allowed to see two of the four classes.

class Numbers:

''' Collection of our number sequence '''

def __init__(self, nums):

self.nums = nums

self.iterator_type = 0

def set_iterator(self, iterator_type):

if iterator_type < 0 or iterator_type > 2:

return

self.iterator_type = iterator_type

def __iter__(self):

assert self.iterator_type >= 0 and self.iterator_type <= 2

if 0 == self.iterator_type:

return LogicalIterator(self.nums)

if 1 == self.iterator_type:

return GreedyIterator(self.nums)

return FairIterator(self.nums)

class LogicalIterator:

''' gets the next number that is next in the sequence '''

def __init__(self, nums):

self.nums = nums

self.cursor = 0

def __next__(self):

if self.cursor >= len(self.nums):

raise StopIteration("end")

value = self.nums[self.cursor]

self.cursor += 1

return value

class GreedyIterator:

''' gets the next smallest number in the sequence '''

...

class FairIterator:

''' gets the next number that is not the same as the previous one returned

'''

...

You are tasked to produce test cases for each of the three iterator classes LogicalIterator,

GreedyIterator and FairIterator based on document string description provided by the

class.

There should be at least 4 good test cases for each of the iterators. The actual output of a sequence

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 20 of 26

remains unknown. Be sure to clearly indicate the input and expected output.

How the sequence is visited using a for loop.

nums = Numbers([5, 8, 4, 1])

nums.set_iterator(1)

for i in nums:

print(i)

One test case:

Input Iteration Expected

”5, 8, 4, 1” 1 5

”5, 8, 4, 1” 2 8

”5, 8, 4, 1” 3 4

”5, 8, 4, 1” 4 1

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 21 of 26

The End. Make sure you answered every question.

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 22 of 26

Extra working

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 23 of 26

Extra working

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 24 of 26

Extra working

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 25 of 26

Notes and reminders

Common types: int, float, bool, str

Common escape characters: \n \t \' \" \\

List terms: [ ]

Type information: type(), dir() isinstance()

Parsing methods: int(), float(), str()

Collection classes: list, dict, set, tuple

Collection methods and functions: append, insert, remove, pop, index, reverse, copy

Keywords

def – Keyword for defining a function

yield – Returns a value from a generator object

import – Imports a module for your program

raise – Raises an exception

break, continue, return, assert

Common Modules

sys – module, provides access to command line arguments.

os.path – module, provides access to checking file paths.

iterable collection operations:

sorted() – sort the iterable collection

reversed() – reversed the iterable collection

list(iterable) – returns a copy of list whose items are the same and in the same order as

iterable items

len – returns the length of the iterable collection

next – returns the next item in the iterator, otherwise raises StopIteration

iter – returns an iterator using the object passed

Control Flow Syntax:

• try: . . . except [. . . as . . . ]: . . . [ finally: . . . ]

• for . . . in . . . : . . . [else: . . . ]

• while . . . : . . . [else: . . . ]

• if . . . : . . . [elif . . . : . . . ] [else: . . . ]

Common Exceptions: Exception, EOFError, ZeroDivisionError, SyntaxError,

AssertionError, KeyError, FileNotFoundError, IndexError, NameError.

INFO1110/COMP9001; Introduction to Programming (S1 2018) Page 26 of 26

Arithmetic Operators: + - * / // **

Logical Operators: not and or == != >= <= < >

Bitwise Operators: & | ˆ << >>

Assignment Operators: = += *= -= /=

Useful functions, methods and constructors:

Input/Output functions:

input() – Allows for reading from standard input

open(filepath, mode) – Opens a file for reading, writing or append.

File access mode 'r' – Read mode 'w' – Writing mode 'a' – Append mode

File methods:

close() – Closes the file

read(n) – Reads n characters from the file

readline() – Reads all input up until a new line

readlines() – Reads all lines from the file

flush() – Writes data stored in the buffer to the file immediately

write() – Writes data to a file

print() – Write the string representation of the object(s) to standard out

String methods (str):

== – Check if this string is equal to the other string

s[i] – Gets a character from s at index i

split – Splits a string based on a delimiter, returns a list of strings

lower – Returns a string in lowercase

upper – Returns a string in uppercase

strip – Returns a string after characters matching a pattern are eliminated from the start and

end of the string.

format – Returns a formatted version of the string. Using substitution from mapping.

Substitutions are identified by braces { and }


版权所有:编程辅导网 2021 All Rights Reserved 联系方式:QQ:99515681 微信:codinghelp 电子信箱:99515681@qq.com
免责声明:本站部分内容从网络整理而来,只供参考!如有版权问题可联系本站删除。 站长地图

python代写
微信客服:codinghelp