Back to the topic

The mark scheme starts on a new page, so you can print pages one and two for a student and keep the last page yourself. Everything prints in black on white whichever theme you are using.

Python · Advanced 6

The Standard Library Toolbox

Section A: 10 multiple choice questions, 10 marks. Section B: 5 written questions, 19 marks. Total 29 marks.

Name

Class

Date

Mark  / 29

Section A

Circle the letter of the correct answer. One mark each.

  1. 1Which collections type is best for counting how many times each word appears?1
    1. ACounter
    2. BChainMap
    3. Cdeque
    4. Dnamedtuple
  2. 2Why is a deque better than a list for a queue with many items?1
    1. AIt keeps the items sorted
    2. BIt uses less memory
    3. CRemoving from the front is O(1) instead of O(n)
    4. DIt cannot overflow
  3. 3What does defaultdict(list) do when you use a key that is not there yet?1
    1. AReturns None
    2. BRaises a KeyError
    3. CReturns 0
    4. DCreates an empty list for that key
  4. 4What is the purpose of bisect?1
    1. ATo sort a list
    2. BTo split a list into two halves
    3. CTo find where a value belongs in a sorted list by binary search
    4. DTo remove duplicates
  5. 5Which module should be used to generate a password reset token?1
    1. Arandom
    2. Bsecrets
    3. Ctime
    4. Dmath
  6. 6What does json.loads do?1
    1. ALoads a file from the internet
    2. BTurns JSON text into Python data
    3. CTurns Python data into JSON text
    4. DWrites Python data to a file
  7. 7When the csv module reads a file, what type are the values?1
    1. AFloats where possible
    2. BWhatever type they look like
    3. CIntegers where possible
    4. DStrings
  8. 8Why should Decimal be created from a string, as in Decimal('0.1')?1
    1. AA float such as 0.1 is already inexact
    2. BStrings are faster
    3. CIt saves memory
    4. DDecimal cannot take numbers
  9. 9What does a seed do for a random number generator?1
    1. AMakes it more random
    2. BLimits the range of numbers
    3. CMakes it produce the same sequence every time
    4. DMakes it faster
  10. 10Why use cursor.execute('... where name = ?', (name,)) instead of joining the name into the SQL string?1
    1. AThe value cannot be treated as SQL, so injection is prevented
    2. BIt is shorter
    3. CIt runs faster
    4. DStrings cannot contain quotes

Section B

Answer in the space provided. The number of marks tells you how many separate points to make.

  1. 1ExplainA program uses a list as a queue, removing items from the front with pop(0). Explain why a deque would be a better choice when the queue is very long.3
  2. 2StateThe program shown is run. State the values output by each of the two print statements.3
    Python
    from collections import Counter, defaultdict
    
    words = "the cat sat on the".split()
    print(Counter(words).most_common(2))
    
    groups = defaultdict(list)
    for word in words:
        if word not in groups[len(word)]:
            groups[len(word)].append(word)
    print(dict(groups))
  3. 3ExplainA shop's program stores prices and calculates totals using floating point numbers. Explain why this can produce incorrect totals, and describe how Python's decimal module avoids the problem.4
  4. 4ExplainExplain what is meant by serialisation, and give one example of a format that is used for it.3
  5. 5DiscussA web application builds an SQL query by joining the text that a user types into a login form to the rest of the query. Discuss why this is a problem, and how the program should be changed.6

Mark scheme

Section A

1A2C3D4C5B6B7D8A9C10A

Section B

1 A program uses a list as a queue, removing items from the front with pop(0). Explain why a deque would be a better choice when the queue is very long. 3

One mark for each of the following, to a maximum of 3.

  • Removing the first item of a list means every other item has to be moved along one place
  • So the time for this grows with the length of the list, O(n)
  • A deque can remove from either end in constant time, O(1)

Model answer. Removing the first item of a list means that every other item has to be moved along one place, so the time taken grows with the length of the list, which is O(n) and slow for a long queue. A deque can add and remove at either end in constant time, O(1), no matter how long it is, so it is a much better choice.

2 The program shown is run. State the values output by each of the two print statements. 3

One mark for each of the following, to a maximum of 3.

  • The first print outputs [('the', 2), ('cat', 1)]
  • The word the appears twice, and the first print shows the two most common
  • The second print outputs {3: ['the', 'cat', 'sat'], 2: ['on']}

Model answer. The first print outputs [('the', 2), ('cat', 1)] because Counter counts the words and most_common(2) gives the two commonest, the appearing twice and cat (the first of the words that appear once) after it. The second print outputs {3: ['the', 'cat', 'sat'], 2: ['on']} because the defaultdict groups the words by their length, creating a new list for each length when it is first used.

3 A shop's program stores prices and calculates totals using floating point numbers. Explain why this can produce incorrect totals, and describe how Python's decimal module avoids the problem. 4

One mark for each of the following, to a maximum of 4.

  • Floating point numbers are stored in binary, and many decimal fractions such as 0.1 cannot be stored exactly
  • So small errors (rounding errors) are introduced, which can build up in calculations
  • The decimal module stores numbers as decimal digits, so values like 19.99 are held exactly
  • The results of calculations are exact and rounding can be controlled, which is important for money

Model answer. Floating point numbers are stored in binary, and many decimal fractions, such as 0.1 or 19.99, cannot be stored exactly in binary. Small rounding errors are therefore introduced, and these can build up in calculations so that totals are slightly wrong. The decimal module stores numbers as decimal digits, so a value such as 19.99 is held exactly, and the results of calculations are exact and the way they are rounded can be controlled, which is important for money.

4 Explain what is meant by serialisation, and give one example of a format that is used for it. 3

One mark for each of the following, to a maximum of 3.

  • Serialisation is converting data structures (objects) into a format that can be stored or sent
  • so that the data can be saved to a file or sent over a network
  • and later rebuilt, for example JSON, XML or CSV

Model answer. Serialisation is converting a data structure, such as a dictionary or an object, into a format that can be stored in a file or sent over a network, so that it can later be rebuilt from that format. JSON is an example of a format used for it, in which data is written as text using objects and arrays.

5 A web application builds an SQL query by joining the text that a user types into a login form to the rest of the query. Discuss why this is a problem, and how the program should be changed. 6

One mark for each of the following, to a maximum of 6.

  • The user can type SQL commands into the form, which are then run by the database (SQL injection)
  • An attacker could log in without a password, or read, change or delete data
  • The input is not treated as data but as part of the command
  • The program should use a parameterised query, with a placeholder for the value
  • The database then treats the input only as data, whatever characters it contains
  • Input should also be validated, and the database account given only the permissions it needs

Model answer. If the text typed by the user is simply joined into the query, the user can type SQL commands into the form and the database will run them. This is called SQL injection. An attacker could log in without knowing a password, or read, change or delete data. The problem is that the input is not treated as data but as part of the command. The program should be changed to use a parameterised query, with a placeholder where the value goes and the typed value supplied separately, so that the database treats it only as data whatever characters it contains. The input should also be validated, and the database account used by the application should be given only the permissions that it needs.