Appendix 1: Programming Challenge Solutions#
Each session in this module features one or more programming challenges. We’ll give you a week or so to try and get the answers yourself, but then you will be able to see solutions here.
Remember though that nearly always there is more than one way to solve the challenge - if your code works it’s right, even if it is different from what you see here!
Session 2: Strings and Things#
Programming Challenge
Create a text file called words.txt
with whatever content you like, and write a Python program to print out how many characters it contains.
Hint: Look at the program hello.py
you wrote in the previous session.
Possible solution#
words_file = open('words.txt')
all_the_text = word_file.read()
words_file.close()
print(len(all_the_text))
Stretch challenge
Adapt your Python program so:
It starts by prompting you for the name of the file to analyse.
It prints the message: “File X contains N characters”. Where X is the name of the file and N is the number of characters.
Possible solution#
words_file_name = input('Name of file to analyse: ')
words_file = open(words_file_name)
all_the_text = word_file.read()
words_file.close()
print('File ', words_file_name, ' contains ', len(all_the_text), ' characters')
Session 4#
Programming Challenge 2
It’s great that we now have a way of taking information from a file and storing it in a data structure - but those \n
characters are annoying.
Can you adapt the code so that they get removed when the data is loaded?
Hint
Remember about string slicing? Can you see why it was helpful you added that extra space character to the last line of the file?
Possible solution#
elements_file = open('elements.txt')
elements = []
for line in elements_file:
elements.append(line[:-1]) # Strip off the final character
elements_file.close()
print(elements)
Stretch Challenge
Create a second data file called “more_elements.txt” and add a few lines with extra element names to it (maybe Sulfur, Phosphorus - whatever you like). Now can you adapt the code you have written so that it reads the contents of both element.txt
and more_elements.txt
into a single list
object, and then prints it out?
Hint
Remember the append()
method of lists?
Possible solution#
elements_file = open('elements.txt')
elements = []
for line in elements_file:
elements.append(line[:-1]) # Strip off the final character
elements_file.close()
# Now add data from the second file:
more_elements_file = open('more_elements.txt')
for line in more_elements_file:
elements.append(line[:-1]])
more_elements_file.close()
print(elements)
Session 5: Numbers#
Programming Challenge
In a fresh cell at the bottom of your notebook, write Python code to calculate and print the sum of all the numbers in the file numbers.txt
. Try to write it in a way that will work no matter now many numbers are in the file (as long as there is only one number per line, and there is a space character after the number in the last line. Note: For this challenge you can assume all the numbers in the files are float
s!).
Hint
You can update the value of a variable with code like: sum = sum + value
- could this be useful within an iteration loop?
Possible Solution
sum = 0.0
numbers_file = open('numbers.txt')
for line in numbers_file:
value = float(line[:-1])
sum = sum + value
numbers_file.close()
print('The sum of the numbers is ', sum)
Session 6: Decision Time
Programming Challenge
Once you feel confident, edit the third line, replacing the >
operator with the <
operator. You can probably guess what this does, in which case you will have worked out that for it to give correct and useful output, you are going to need to edit the messages in lines 2 and 4 as well. Can you make it work right, whatever number you set mass
to?
Once you have cracked this, try to repeat with the logical comparison operators >=
, <=
, and finally !=
.
Possible (partial) solution:
mass = 12.0
identity = 'Carbon or heavier'
if mass < 12.0:
identity = 'Lighter than carbon'
print(identity)
Programming Challenge 1
Update the program ‘analyze.py’ that you wrote in the last session, so that it no longer requires the last number in the file ‘numbers.txt’ to have a space character after it.
In addition to getting the program to print out the sum of the numbers in the file, write extra code to get it to print out the mean as well.
Possible solution:
sum = 0.0
number_of_values = 0
numbers_file = open('numbers.txt')
for line in numbers_file:
number_of_values = number_of_values + 1
if line[:-1] == '\n':
value = float(line[:-1])
else:
value = float(line)
sum = sum + value
numbers_file.close()
print('The sum of the numbers is ', sum)
print('The mean of the numbers is ', sum / number_of_values)
Stretch Challenge
Mental Floss gives a suggestion for the age ranges that define Gen Z, Millenials, etc. Write a standalone Python program that askes the user to input their age, and then tells them which group they belong to.
Possible Solution:
age_string = input('Enter your age in years: ')
age = int(age_string) # convert from a string to an integer
if age < 13:
print('You are Gen Alpha')
elif age < 29:
print('You are Gen Z')
elif age < 45:
print('You are a Millenial')
elif age < 61:
print('You are Gen X')
elif age < 80:
print('You are a Baby Boomer')
else:
print('You belong to the Silent Generation')