MAS212 Class Test (Mock) with answers

(This is a mock test. The real Class Test 1 will look similar and will be held in Week 2.)

Aim:

  • To help you learn enough about Python to enjoy the remainder of this course.

How it works:

  • Complete the notebook below, as follows. First, click on a question, then from the menu select Insert -> Insert Cell Below. From the dropdown box (next to the "stop" symbol) choose whether you wish to insert 'Code' or 'Markdown' (i.e. text). Save regularly!
  • Press Shift-Enter to execute the code in a cell.
  • Submit via http://mas212.group.shef.ac.uk/uploads by 5pm on Mon 29th Oct.
  • Your lecturer will mark each question as either 2 (good), 1 (needs revision), 0 (not attempted/wrong). You will then be given one chance to revise your answers and resubmit.
  • This is an open-book test, which means you may consult books, notes and internet resources. However, copy-and-pasting is strongly discouraged, and would reflect badly on a Level 2 University of Sheffield student. Please give answers in your own words.

Key Resources:

  • Chapter 1 in https://scipy-lectures.github.io/


1. The Python language

(Please answer the following questions in "raw text" or "markdown" cells)

Q. Python is case-sensitive: True or false?

True

Q. Python has four numeric types -- what are they?

Python 2.7 has four numeric types : int, float, long, and complex. Python 3.4 has only three, as the long type has been removed, as ints may now be arbitrarily large.

Q. Describe in your own words the int and float data types.

int is a representation of an integer, i.e., a whole number. float is a representation of a real number. In Python, as in other languages, this is represented internally by a mantissa and exponent (e.g., $1.2345$ may be represented as $12345 \times 10^{-4}$).

N.B. For real numbers with arbitrary precision, use the decimal module.

Q. Python has several container types. Give three examples.

Any three of: list, string, dict, set and tuple.

Note that you can use type() to find out the type of any object.

In [3]:
print(type([0, 1, 2]))        # list
print(type("I love tests!"))  # str (string)
print(type({'pi': 3.1415926, 'e': 2.7182818, 'gamma': 0.5772157}))  # dict (dictionary). Here, mathematical constants.
print(type(set([0, 2, 0, -1, 2])))   # set (a set is like a list with no ordering & no duplicates)
print(type((1,2)))            # tuple
<class 'list'>
<class 'str'>
<class 'dict'>
<class 'set'>
<class 'tuple'>

Q. What does mutable mean? Give an example of mutable and unmutable sequences.

Mutable means "can be changed". A list is mutable: it can be modified in-place. A tuple is immutable: attempting to change it will cause an error. For example,

In [4]:
a = [1, 2, 3]  # list
a[0] = 5
print(a)
[5, 2, 3]
In [5]:
b = (1,2,3)  # tuple
b[0] = 5     # will throw an error
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-7dcda44f0f18> in <module>()
      1 b = (1,2,3)  # tuple
----> 2 b[0] = 5     # will throw an error

TypeError: 'tuple' object does not support item assignment

Strings are also immutable. In order to change a string, a new string must be created.

For example, in the code below, the function replace (which is a member of the str class) creates a new string, which is assigned to d.

In [6]:
c = "Hello everyone."
d = c.replace("Hello", "Goodbye")
print(c + " " + d)
Hello everyone. Goodbye everyone.


2. Simple Python code

(Please answer the following questions in "code" cells).

Q. Python as a calculator: Calculate $3 + 4$, $3 \times 4$, $3 / 4$, $3^2 + 4^2$ and $(3 + 4i)^{3}$.

In [7]:
[3+4, 3*4, 3 / float(4), 3**2 + 4**2, complex(3,4)**3]  
Out[7]:
[7, 12, 0.75, 25, (-117+44j)]

Q. Use for loop to find the sum-of-squares $1 + 4 + 9 + \ldots + 100$

In [9]:
tot = 0
for i in range(1,11):  # i in the range 1 to 10
    tot += i**2
print("The answer is %d" % tot)    # (If this syntax is unfamiliar, read up on string formatting)
The answer is 385

Q. Make a list of square numbers $[1, 4, 9, \ldots, 100]$ and find the sum another way

In [10]:
l = [i**2 for i in range(1,11)]
sum(l)
Out[10]:
385

Q. Print the value of $\pi$ to 10 decimal places. (Hint: first import the "math" package).

In [12]:
import math
print("pi = %.10f" % math.pi)
pi = 3.1415926536

Q. Compute the first 20 terms in the Fibonacci sequence, defined by $f_{k+1} = f_k + f_{k-1}$ with $f_{0} = f_{1} = 1$.

In [13]:
fib = [1,1]
for k in range(18):
    fib.append(fib[-1]+fib[-2])
print(fib)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]

Q. Print the value of Pi to 20 decimal places. (Hint: import the math package).

In [14]:
import math
print("%.10f" % math.pi)
3.1415926536

Q. Write a function to find all the divisors of a positive integer. Test it by finding all divisors of 2014.

In [15]:
def divisors(N):
    return [i for i in range(1,N+1) if N % i == 0]
divisors(2014)
Out[15]:
[1, 2, 19, 38, 53, 106, 1007, 2014]

Q. Calculate all perfect numbers less then 10000.

In [16]:
[i for i in range(2,1000) if sum(divisors(i)[:-1]) == i]
# Note that "proper divisors" do not include the number itself.
Out[16]:
[6, 28, 496]


3. String processing

In [17]:
s = "The horse has a long neck"

Q. How many characters are in this string?

In [18]:
len(s)
Out[18]:
25

Q. Replace the word "horse" with "giraffe".

In [19]:
print(s.replace("horse", "giraffe"))
The giraffe has a long neck

Q. Use list slicing to (a) print every third character, (b) print the second half of the string, (c) reverse the string.

In [21]:
print(s[::3]) # every third character
print(s[len(s)//2:]) # second half of string
print(s[::-1])  # reversed string
T r s nnk
s a long neck
kcen gnol a sah esroh ehT

Q. How many times does the letter "e" appear in this string?

In [22]:
s.count("e")
Out[22]:
3

Q. Which words in the sentence contain the letter "e"?

In [23]:
[w for w in s.split(" ") if "e" in w]
Out[23]:
['The', 'horse', 'neck']


4. A slightly harder question

In [24]:
s2 = "Ju jt b usvui vojwfstbmmz bdlopxmfehfe uibu b tjohmf nbo jo qpttfttjpo pg b hppe gpsuvof nvtu cf jo xbou pg b xjgf"

Q. Decipher the string above. From which novel is it taken?

Note that characters may be turned into integers (ASCII codes) using ord() and back again using chr().

It looks like a Caesar shift has been applied (note the '-' character suggests it has been done crudely based on ASCII code). Below is a function which shifts the letters by k steps. Shifting by -1 does the trick here. It's from Pride and Prejudice by Jane Austen.

In [27]:
def caesar(s, n):
    alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV"
    l = [chr(ord(c)+n) if c in alphabet else c for c in list(s)]
    return "".join(l)

caesar(s2, -1)
Out[27]:
'It is a truth universally acknowledged that a single man in possession of a good fortune must be in want of a wife'
In [ ]: