Terms Test 3 April 2014 NWEN 241 SYSTEMS PROGRAMMING
Transcription
Terms Test 3 April 2014 NWEN 241 SYSTEMS PROGRAMMING
Terms Test 3 April 2014 NWEN 241 SYSTEMS PROGRAMMING Time allowed: 50 minutes Instructions: The test contains 4 questions. You should attempt ALL questions Each question is worth 10 marks. The exam consists of 40 marks in total. Non-programmable calculators are allowed. Paper foreign to English language dictionaries are allowed. Electronic dictionaries and programmable calculators are not allowed. NWEN241 Page 1 of 11 Question 1 - Python fundamentals [10 marks] a) [4 marks] Some of following strings are legal python3 identifiers and some are not. For each one state if the name is legal or not and if not, explain why: i) global not legal – Python keyword ii) 4squared not legal – variables can’t start with an number iii) square-root not legal – hyphen (‘-‘) is not a legal character iv) daysOfWeek legal – uppercase letters are OK NWEN241 Page 2 of 11 b) [6 marks] For each of the following Python keywords, briefly explain what it does and write a short piece of code to illustrate its use. i) try The try keyword is used to allow a section of code to be run and have an exception handled if it fails: #!/usr/bin/env python3 f = None try: f = open('films', 'r') for i in f: print i, except IOError: print "Error reading file" finally: if f: f.close() ii) in The in keyword. #!/usr/bin/env python3 print (4 in (2, 3, 5, 6)) for i in range(25): print (i, end=” ”) print(””) In this example, the in keyword tests if the number four is in the tuple. The second usage is traversing a tuple in a for loop. The built-in function range() returns integers 0 .. 24. NWEN241 Page 3 of 11 Question 2 – Writing a Python program [10 marks] a) [10 marks] Write a python3 program that reads a filename from the command line, opens a file and prints the contents on the screen. For example, it might be called by: $ python3 printfile.py filename Your program issue appropriate error messages and return values. #!/usr/bin/env python3 # import Python libraries import os import sys # get the name of our program with # leading dirname removed progname = os.path.basename(sys.argv[0]) def usage(): print('Usage: {0} <filename>'.format(progname)) sys.exit(1) # process the inputs from the user if len(sys.argv) == 2: # read inputs and convert to integers try: filename = sys.argv[1] except ValueError: usage() else: # tell user inputs were not acceptable usage() sys.exit(1) try: with open(filename) as fin: for line in fin: print(line.rstrip()) fin.close() except: print("ERROR: {0} couldn't open file '{1}'".format(progname, filename)) sys.exit(1) sys.exit(0) NWEN241 Page 4 of 11 Question 3 – Reading a Python program [10 marks] Consider the following python3 program. #! /usr/bin/env python3 # # Declare a string with all the alphanumeric characters # alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' # # (1) # def some_varencode(number): # # Check that number is an integer # if not isinstance(number, int): raise TypeError('number must be an integer') # # Zero is a special case # if number == 0: return '0' # # (2) # sign = '' if number < 0: sign = '-' number = - number # # (3) # some_var = '' while number != 0: number, i = divmod(number, len(alphabet)) some_var = alphabet[i] + some_var # # (4) # return sign + some_var # # (5) # def some_vardecode(some_var): return int(some_var, len(alphabet)) print(some_varencode(34)) print(some_varencode(1234)) print(some_vardecode('R')) print(some_vardecode('QCH')) HINT: The built-in function divmod(x, y) takes two numbers as arguments and returns a pair of numbers consisting of their quotient and remainder when using long division e.g. divmod(7,3) -> (2, 1). NWEN241 Page 5 of 11 a) [5 marks] The code contains 5 numbered places where comments are required. Write 5 suitable comments in the box below. Comments (1) and (5) should describe what the complete function does and comments (2) to (4) should describe the section that follows. NWEN241 Page 6 of 11 NWEN241 Page 7 of 11 1) Encode a base 10 number in base 36 2) Record the 'sign' of the input and make sure the number to be converted is positive. 3) Convert the number to base 36 using divmod(x,y) to calculate the result 4) Return the converted value with the given 'sign' 5) Convert a base 36 number to base 10 NWEN241 Page 8 of 11 b) [5marks] The functions in the program above are called with the following values: print(some_varencode(34)) print(some_varencode(1234)) 34th element of the alphabet => Y print(some_vardecode('R')) print(some_vardecode('QCH') >>> divmod(1234,36) (34, 10) 34 -> 'Y' 10 -> 'A' YA 'R' - > 27th element of the alphabet 'Q' -> 26 'C' -> 12 'H' -> 17 (((26 * 36) + 12) * 36) + 17 34145 What is the result in each case? NWEN241 Page 9 of 11 Question 4 – Interfacing with other systems [10 marks] a) [6 marks] We can call programs written in C (and other languages) from python3 using a toolkit like the Simplified Wrapper and Interface Generator (SWIG). Briefly outline three tasks that need to be done by the SWIG extension code to make this possible. We need extension code to: 1. Convert data values from Python to C, 2. Perform a function call to a C routine using the converted values, and 3. Convert the data values from the call from C to Python. NWEN241 Page 10 of 11 b) [5 marks] The following commands were used to delete some records on a database server. # Prepare SQL query to DELETE required records sql = "DELETE FROM EMPLOYEE WHERE AGE > 20” # Execute the SQL command cur.execute(sql) The psycopg2 library provides two operations (conn.commit() and conn.rollback()) that we need to use after we make such changes. Write a short code fragment to illustrate the correct use of these operations. You should include comments that describe what the operations are doing. # Prepare SQL query to DELETE required records sql = "DELETE FROM EMPLOYEE WHERE AGE > 20” try: # Execute the SQL command cur.execute(sql) # Commit your changes in the database conn.commit() except: # Rollback in case there is any error conn.rollback() NWEN241 Page 11 of 11