Exam practice
Every question from the end of every unit, with hints and answers to open. After you check an answer, mark how you did, and come back to the ones you didn’t get.
10 questions
Unit 3 · Python: Lists, Strings and Dictionaries
What is a data structure? Name four of Python’s, with an example of each written as Python, and say one job each suits.
Answer
A data structure is a way of holding many values so that a program can store them, find them and change them.
- List,
[52, 38, 71]: values in order, which can change; marks to average, a queue. - String,
"Bhaktapur": a sequence of characters that can’t change; text, a message. - Tuple,
("Bagmati", 13): a few values that belong together and don’t change; a date, a point. - Dictionary,
{"tea": 25}: values found by a key; prices by item, counts of words.
colors = ["blue", "white", "red", "green", "yellow"]. Give the value of each: i. colors[1] ii. colors[-1] iii. colors[1:3] iv. colors[:2] v. len(colors[2:]) vi. colors.index("red")
Answer
- i.
"white" - ii.
"yellow"(the last) - iii.
["white", "red"](positions 1 and 2) - iv.
["blue", "white"] - v.
3(the slice is["red", "green", "yellow"]) - vi.
2
Write the output of this program.
nums = [4, 7, 1]nums.append(9)nums.insert(1, 5)x = nums.pop()nums.remove(7)print(nums, x)Answer
Output
[4, 5, 1] 9After append(9): [4, 7, 1, 9]. After insert(1, 5): [4, 5, 7, 1, 9]. pop() takes out the last, 9, into x: [4, 5, 7, 1]. remove(7): [4, 5, 1].
What is the difference between a list and a dictionary? Explain with an example of the same data kept both ways, and say which you would choose for it, and why.
Answer
A list keeps values in order and finds them by their position, a number from 0. A dictionary keeps key–value pairs and finds a value by its key, a name you choose; a key comes only once.
The same marks: as a list, marks = [72, 58, 90], where marks[1] is 58 but nothing says whose it is; as a dictionary, marks = {"Aarati": 72, "Bikash": 58, "Chhiring": 90}, where marks["Bikash"] is 58.
To find a student’s marks by name, the dictionary is better: one step, and the name is kept with the marks. To work out the class average, or to sort the marks, a list is enough, since every value is used in turn and names don’t matter.
Write a program that asks for a sentence and prints how many words it has, the longest word, and the sentence with its words in reverse order.
Answer
sentence = input("A sentence: ")words = sentence.split()print(len(words), "words")longest = ""for w in words: if len(w) > len(longest): longest = wprint("Longest:", longest)print(" ".join(words[::-1]))Output
A sentence: we climbed to the top of Nagarkot7 wordsLongest: NagarkotNagarkot of top the to climbed wesplit() gives the list of words; the highest-so-far pattern compares their lengths; words[::-1] is the list reversed, and join() glues it back together with spaces.
Write a program that counts how many times each letter comes in a word the user types, using a dictionary. Show its output for banana.
Answer
word = input("A word: ")counts = {}for ch in word.lower(): counts[ch] = counts.get(ch, 0) + 1print(counts)Output
A word: banana{'b': 1, 'a': 3, 'n': 2}A for loop over a string gives its characters. Each is a key in the tally; get(ch, 0) gives its count so far, or 0 for a new letter.
A student wants to give everyone’s marks a bonus of 5, but this program prints the old marks. Explain why, and correct it in two different ways.
marks = [52, 38, 71]for m in marks: m = m + 5print(marks)Answer
It prints [52, 38, 71]. Each time round, m holds a copy of the item’s value; m = m + 5 changes m only, not the item in the list.
Way 1, change each item through its position:
marks = [52, 38, 71]for i in range(len(marks)): marks[i] = marks[i] + 5print(marks)Way 2, build a new list and put it in the variable:
marks = [52, 38, 71]new = []for m in marks: new.append(m + 5)marks = newprint(marks)Both print [57, 43, 76].
Here is part of a CSV file of bus fares from Kathmandu (made-up fares). Write a program that reads lines like these from a string into a dictionary from town to fare, then prints the fare to Pokhara, and the cheapest town.
Fares
Pokhara,1200Chitwan,900Butwal,1100Dhulikhel,150Answer
text = """Pokhara,1200Chitwan,900Butwal,1100Dhulikhel,150"""fares = {}for line in text.splitlines(): town, fare = line.split(",") fares[town] = int(fare)print("Pokhara:", fares["Pokhara"])cheapest = min(fares, key=fares.get)print("Cheapest:", cheapest, fares[cheapest])Output
Pokhara: 1200Cheapest: Dhulikhel 150Each line is split into a list of two strings, unpacked into town and fare. A dictionary fits, because fares are looked up by town. Instead of min(fares, key=fares.get), the lowest-so-far pattern over fares.items() works too.
Blur the Nyatapola photo: each new pixel is the average of the old one and its neighbors (the 3 × 3 square around it, fewer at the edges). Draw it. Why do the temple’s edges go soft?
Hint
Inside the loops over r and c, two more, for dr in [-1, 0, 1]: and for dc in [-1, 0, 1]:, reach the square around it. Add up and count only pixels on the photo.
Answer
from nyatapola import photofrom pixels import show_grid blurred = []for r in range(len(photo)): row = [] for c in range(len(photo[0])): total = 0 count = 0 for dr in [-1, 0, 1]: for dc in [-1, 0, 1]: if 0 <= r + dr < len(photo) and 0 <= c + dc < len(photo[0]): total = total + photo[r + dr][c + dc] count = count + 1 row.append(total // count) blurred.append(row)show_grid(blurred)Picture
Each new pixel mixes its gray with its neighbors’, so where a dark roof meets the pale sky the jump from dark to light is spread over three pixels instead of one. The test on line 12 matters: on the top row r + dr is −1, and photo[-1] would quietly read the bottom row, with no error.
A shop wants a program to keep its stock: how many of each item it has, and to take an item off when one is sold, refusing a sale when none is left. Design it: choose the data structure and say why, write the algorithm for one sale in pseudocode, then write it as a Python function sell(stock, item) that returns True for a sale and False when it can’t sell.
Answer
Data: a dictionary, key the item’s name, value how many are left: each sale looks up one item by its name, and changes its count.
Pseudocode
IF item is not in stock OR stock of item = 0 THEN RETURN FalseELSE SET stock of item TO stock of item − 1 RETURN TrueEND IFdef sell(stock, item): """Take one item off the stock. Return True if it was sold.""" if item not in stock or stock[item] == 0: return False stock[item] = stock[item] - 1 return True stock = {"copy": 2, "pen": 0}print(sell(stock, "copy"), sell(stock, "pen"), sell(stock, "ruler"))print(stock)Output
True False False{'copy': 1, 'pen': 0}The function changes the dictionary it is given (the shop’s real stock), so the caller sees the new counts, and it returns True or False to say whether the sale happened. item not in stock is checked first, so stock[item] is never looked up for a missing key (or doesn’t look at its right side when the left is already True).
