WEEK
FOUR
Problems for Week 4
We’re into the last two weeks now, so all we’re going to say is good luck!
1 Numbers to words
My computer speaks to me. No, really — if I can’t or don’t want to read what’s on the screen, I can have the
computer read it out to me. One part of that is reading out numbers: the computer has to figure out that when a
number appears on the screen, it has to read out the number in words. For example, if the number “8123” appears
on the screen, then my computer will say “eight one two three”.
Your job here is to do that translation. Your program will read a single line of input, which will contain a number.
It should print out the words the computer would say for that number.
So for the example above, the input will be
8123
and you need to output
eight one two three
My computer is pretty dumb about this: it doesn’t convert “33” to “thirty three”, but just says “three three”.
2 Merge files in order
Have you ever wanted to sort a really large amount of data? No? ... Well, don’t worry, I’m sure you will one day.
Fortunately, computer scientists have spent the past 50 years thinking up ways to sort stuff very quickly, so when
that day comes you’ll probably just use an algorithm someone else has implemented. An algorithm is basically
just a set of instructions for solving a particular problem — in this case putting a list in sorted order.
If you’re taking a software design or computing course, you might have heard of Bubble sort. Bubble sort is a
simple algorithm, but unfortunately it can take a really long time to sort large amounts of data. In fact, the time it
takes to sort a list grows at least as fast as the length of the list squared. So if you have two lists, and one is three
times longer than the other, then it will take 9 times as long to sort the longer list, and if the second list was ten
times longer then it would take 100 times as long!
Because of this, Bubble Sort is rarely used in practice, and it’s definitely not used in Python’s list.sort.
Instead, many programming languages use faster algorithms like Quick sort which scale a lot better to larger
inputs. However, these algorithms need to fit the data they’re going to sort into RAM to be really quick.
So what do you do if you want to sort more data than you can fit in main memory? Well, you could buy more
memory, but if that’s not an option then you could read the first half of your data into memory, sort it and write
that out to a file, then read the second half and sort it and write that out to a file. Then all you have to do is merge
the two sorted files! This is sometimes called external sorting, and it’s used in some really big databases.
Except it’s not really that easy, which is why we’re setting it as a Challenge question...
Your task is to read in two sorted files and print the result of merging those two files. The files will be called
file1.txt and file2.txt, and we promise they will both be in sorted order.
For example, if file1.txt contains:
c National Computer Science School 2005-2009 1
NCSS Challenge (Beginners) WEEK FOUR
cat
dog
pumpkin
and file2.txt contains:
elephant
giraffe
hippogriff
then your program should output:
cat
dog
elephant
giraffe
hippogriff
pumpkin
While using a for loop to read in all the lines of a file is quite neat, sometimes it’s handy to have greater control
over which line of a file to read in. After opening a file using open(’filename.txt’, ’rU’), you can use the
readline() function to read the next line of the file. So for example, if you wanted to print out only the first 10
lines of a file, you could do so like this:
f = open(’filename.txt’, ’rU’)
for i in xrange(10):
print f.readline()[:-1]
Remember to remove the last character in the line (use the [:-1]) because, just like when reading lines in using
a for loop, readline() keeps the newline character on the end of the line.
Hint
Can you do this without using list.sort?
3 Substitute
A substitution cipher is a way of encrypting text that involves scrambling the letters of the alphabet to make a
key, then mapping each letter in the original message to the corresponding letter in the key.
To make things clearer, we’ll assume that the original message is in lower case and we encrypt to upper case. For
example, given this mapping:
abcdefghijklmnopqrstuvwxyz
JILSPENXKMWUCVTDYHBROZFGAQ
The message:
hello world
would be encoded:
XPUUT FTHUS
I’ve written some Python code that you can download to generate a random key and encrypt a string:
c National Computer Science School 2005-2009 2
NCSS Challenge (Beginners) WEEK FOUR
import random, string
key = list(string.uppercase)
random.shuffle(key)
mapping = {}
for i in xrange(len(key)):
mapping[string.lowercase[i]] = key[i]
# Don’t edit the code above this comment
ciphertext = ""
for c in "helloworld":
ciphertext += mapping[c]
print ciphertext
This code has two problems:
• I want to read one line of input and encrypt that, rather than encrypting "helloworld".
• At the moment, it doesn’t deal with characters in the input other than lower case letters: I want it to just
pass through to the output without changing them.
Can you fix it for me?
Hint
You don’t need to understand how the code before ciphertext = "" works to solve this problem. If you aren’t
sure, try printing out the contents of the mapping variable.
4 Banner printer
Have you ever gotten frustrated with trying to draw using a mouse? Don’t have enough money for a graphics
tablet? Never fear! ASCII art is the process of drawing pictures by joining together characters from the ASCII
character set. Anything can be drawn, from people’s pets to everyone’s favourite Vulcan.
Pictures take a lot of imagination, though, so this question deals with something a little simpler — text. Your
task is to take a line of input and print it out in as a banner in a different font, much like they do in the ASCII
Generator.
Your program needs to read in 3 lines from input and one file. The first line of input is the height of each letter
in the font, the second is how many characters wide a space in the font should be, and the third is the message to
be banner-ised. The message will only ever contain uppercase letters and spaces.
The font file will be called font.txt. It contains a list of all 26 letters of the alphabet in uppercase, set out one
under the other. An example font.txt file can be downloaded from our site.
So, for the input
8
4
HI THERE
and the example font.txt file, the output would be:
_________ _________ _______ _______ _______
| /|__ __/ __ __/| /|( ____ ( ____ )( ____ 
| ) ( | ) ( ) ( | ) ( || ( /| ( )|| ( /
| (___) | | | | | | (___) || (__ | (____)|| (__
| ___ | | | | | | ___ || __) | __)| __)
| ( ) | | | | | | ( ) || ( | ( ( | (
| ) ( |___) (___ | | | ) ( || (____/| )  __| (____/
|/ |_______/ )_( |/ |(_______/|/ __/(_______/
c National Computer Science School 2005-2009 3
NCSS Challenge (Beginners) WEEK FOUR
This font (the one you can download above) is 8 characters high (the first value read from the user) and the space
between HI and THERE is 4 spaces wide (the second value read from the user).
And credit where credit’s due — the example font in this question is called Epic, taken from figlet.org.
5 Sudoku checker
We want you to write a program to check our Sudoku puzzle solutions are correct. If you haven’t seen Sudoku,
you can read about it here. A Sudoku puzzle is a 9x9 square, and each space needs to hold a digit. Digits cannot
repeat in a row, a column, or in the nine 3x3 grids created by dividing the 9x9 square into thirds vertically and
horizontally.
So far we’ve got code that tries to read in our solution and check that the rows satisfy the rule that there are no
repeats in each row:
puzzle = []
row = raw_input()
while row:
puzzle.append(row)
row = raw_input()
for row in xrange(9):
seen = {}
for column in xrange(9):
digit = puzzle[column][row]
if digit in seen:
print ’duplicate’, digit, ’in row’, row
else:
seen[digit] = 1
Unfortunately, it’s just a little bit broken. Also, we’d like the program to check the rows, then the columns, and
then the 3x3 grids for errors. When it finds a duplicate in a row (say 3 appears twice in row 5), it should print:
duplicate 3 in row 5
If the duplicate digit appears three or more times in total, it should only print out the duplicate message once.
The same goes for columns and grids. The grids should be numbered 1 to 9 in the order of left to right and then
top to bottom. For this puzzle with several mistakes:
543678912
672195348
198342567
859761423
426853791
713924856
961537284
287419631
345286179
your program should produce the following output:
duplicate 1 in row 8
duplicate 4 in column 2
duplicate 3 in column 3
duplicate 1 in column 9
duplicate 1 in grid 9
If the puzzle is correct, your program should print absolutely nothing!
c National Computer Science School 2005-2009 4

Questions4

  • 1.
    WEEK FOUR Problems for Week4 We’re into the last two weeks now, so all we’re going to say is good luck! 1 Numbers to words My computer speaks to me. No, really — if I can’t or don’t want to read what’s on the screen, I can have the computer read it out to me. One part of that is reading out numbers: the computer has to figure out that when a number appears on the screen, it has to read out the number in words. For example, if the number “8123” appears on the screen, then my computer will say “eight one two three”. Your job here is to do that translation. Your program will read a single line of input, which will contain a number. It should print out the words the computer would say for that number. So for the example above, the input will be 8123 and you need to output eight one two three My computer is pretty dumb about this: it doesn’t convert “33” to “thirty three”, but just says “three three”. 2 Merge files in order Have you ever wanted to sort a really large amount of data? No? ... Well, don’t worry, I’m sure you will one day. Fortunately, computer scientists have spent the past 50 years thinking up ways to sort stuff very quickly, so when that day comes you’ll probably just use an algorithm someone else has implemented. An algorithm is basically just a set of instructions for solving a particular problem — in this case putting a list in sorted order. If you’re taking a software design or computing course, you might have heard of Bubble sort. Bubble sort is a simple algorithm, but unfortunately it can take a really long time to sort large amounts of data. In fact, the time it takes to sort a list grows at least as fast as the length of the list squared. So if you have two lists, and one is three times longer than the other, then it will take 9 times as long to sort the longer list, and if the second list was ten times longer then it would take 100 times as long! Because of this, Bubble Sort is rarely used in practice, and it’s definitely not used in Python’s list.sort. Instead, many programming languages use faster algorithms like Quick sort which scale a lot better to larger inputs. However, these algorithms need to fit the data they’re going to sort into RAM to be really quick. So what do you do if you want to sort more data than you can fit in main memory? Well, you could buy more memory, but if that’s not an option then you could read the first half of your data into memory, sort it and write that out to a file, then read the second half and sort it and write that out to a file. Then all you have to do is merge the two sorted files! This is sometimes called external sorting, and it’s used in some really big databases. Except it’s not really that easy, which is why we’re setting it as a Challenge question... Your task is to read in two sorted files and print the result of merging those two files. The files will be called file1.txt and file2.txt, and we promise they will both be in sorted order. For example, if file1.txt contains: c National Computer Science School 2005-2009 1
  • 2.
    NCSS Challenge (Beginners)WEEK FOUR cat dog pumpkin and file2.txt contains: elephant giraffe hippogriff then your program should output: cat dog elephant giraffe hippogriff pumpkin While using a for loop to read in all the lines of a file is quite neat, sometimes it’s handy to have greater control over which line of a file to read in. After opening a file using open(’filename.txt’, ’rU’), you can use the readline() function to read the next line of the file. So for example, if you wanted to print out only the first 10 lines of a file, you could do so like this: f = open(’filename.txt’, ’rU’) for i in xrange(10): print f.readline()[:-1] Remember to remove the last character in the line (use the [:-1]) because, just like when reading lines in using a for loop, readline() keeps the newline character on the end of the line. Hint Can you do this without using list.sort? 3 Substitute A substitution cipher is a way of encrypting text that involves scrambling the letters of the alphabet to make a key, then mapping each letter in the original message to the corresponding letter in the key. To make things clearer, we’ll assume that the original message is in lower case and we encrypt to upper case. For example, given this mapping: abcdefghijklmnopqrstuvwxyz JILSPENXKMWUCVTDYHBROZFGAQ The message: hello world would be encoded: XPUUT FTHUS I’ve written some Python code that you can download to generate a random key and encrypt a string: c National Computer Science School 2005-2009 2
  • 3.
    NCSS Challenge (Beginners)WEEK FOUR import random, string key = list(string.uppercase) random.shuffle(key) mapping = {} for i in xrange(len(key)): mapping[string.lowercase[i]] = key[i] # Don’t edit the code above this comment ciphertext = "" for c in "helloworld": ciphertext += mapping[c] print ciphertext This code has two problems: • I want to read one line of input and encrypt that, rather than encrypting "helloworld". • At the moment, it doesn’t deal with characters in the input other than lower case letters: I want it to just pass through to the output without changing them. Can you fix it for me? Hint You don’t need to understand how the code before ciphertext = "" works to solve this problem. If you aren’t sure, try printing out the contents of the mapping variable. 4 Banner printer Have you ever gotten frustrated with trying to draw using a mouse? Don’t have enough money for a graphics tablet? Never fear! ASCII art is the process of drawing pictures by joining together characters from the ASCII character set. Anything can be drawn, from people’s pets to everyone’s favourite Vulcan. Pictures take a lot of imagination, though, so this question deals with something a little simpler — text. Your task is to take a line of input and print it out in as a banner in a different font, much like they do in the ASCII Generator. Your program needs to read in 3 lines from input and one file. The first line of input is the height of each letter in the font, the second is how many characters wide a space in the font should be, and the third is the message to be banner-ised. The message will only ever contain uppercase letters and spaces. The font file will be called font.txt. It contains a list of all 26 letters of the alphabet in uppercase, set out one under the other. An example font.txt file can be downloaded from our site. So, for the input 8 4 HI THERE and the example font.txt file, the output would be: _________ _________ _______ _______ _______ | /|__ __/ __ __/| /|( ____ ( ____ )( ____ | ) ( | ) ( ) ( | ) ( || ( /| ( )|| ( / | (___) | | | | | | (___) || (__ | (____)|| (__ | ___ | | | | | | ___ || __) | __)| __) | ( ) | | | | | | ( ) || ( | ( ( | ( | ) ( |___) (___ | | | ) ( || (____/| ) __| (____/ |/ |_______/ )_( |/ |(_______/|/ __/(_______/ c National Computer Science School 2005-2009 3
  • 4.
    NCSS Challenge (Beginners)WEEK FOUR This font (the one you can download above) is 8 characters high (the first value read from the user) and the space between HI and THERE is 4 spaces wide (the second value read from the user). And credit where credit’s due — the example font in this question is called Epic, taken from figlet.org. 5 Sudoku checker We want you to write a program to check our Sudoku puzzle solutions are correct. If you haven’t seen Sudoku, you can read about it here. A Sudoku puzzle is a 9x9 square, and each space needs to hold a digit. Digits cannot repeat in a row, a column, or in the nine 3x3 grids created by dividing the 9x9 square into thirds vertically and horizontally. So far we’ve got code that tries to read in our solution and check that the rows satisfy the rule that there are no repeats in each row: puzzle = [] row = raw_input() while row: puzzle.append(row) row = raw_input() for row in xrange(9): seen = {} for column in xrange(9): digit = puzzle[column][row] if digit in seen: print ’duplicate’, digit, ’in row’, row else: seen[digit] = 1 Unfortunately, it’s just a little bit broken. Also, we’d like the program to check the rows, then the columns, and then the 3x3 grids for errors. When it finds a duplicate in a row (say 3 appears twice in row 5), it should print: duplicate 3 in row 5 If the duplicate digit appears three or more times in total, it should only print out the duplicate message once. The same goes for columns and grids. The grids should be numbered 1 to 9 in the order of left to right and then top to bottom. For this puzzle with several mistakes: 543678912 672195348 198342567 859761423 426853791 713924856 961537284 287419631 345286179 your program should produce the following output: duplicate 1 in row 8 duplicate 4 in column 2 duplicate 3 in column 3 duplicate 1 in column 9 duplicate 1 in grid 9 If the puzzle is correct, your program should print absolutely nothing! c National Computer Science School 2005-2009 4