CS17 : Modelling


https://docs.google.com/presentation/d/1ijlp24n5LGbgPrAXjlgZzXlLwLV05f8UKE_yaQbriIs/preview
In this section, we look at how we can use computer systems to model real world situations. Specifically, we look at the computational thinking skills or decomposition and abstraction followed by the application of random number generators in computer modelling.

We are learning ...
  • That we can use software to simulate and model aspects of the real world.
So that we can ...
  • Analyse a problem and investigate requirements
    - Initialisation
    - Inputs
    - Processing
    - Output
  • Apply the technique of abstraction to simplify a problem
  • Apply the technique of decomposition to a problem
  • Use random number generators to simulate random events

# Get Ready.png

Activity 1 Analysing a problem, backwards   I   O   A   E 

The four stages of planning any programmed solution

Many computational problems present themselves with little or no clue as to how you are meant to approach their solution. One skill you need is to be able to deconstruct a problem to identify ...
  • What initialisation is required including variables and constants;
  • What inputs are required direct from the user or from other locations;
  • What processing is required in order to transform inputs into outputs (including type casting and conversion);
  • What outputs are required.


Task 1.1 Deconstruction
Where you learn a technique to tackle a problem from the end to the beginning


In your notebooks / on paper

Copy down the diagram above into your notebooks / on paper. Underneath the diagram, describe, in your own words how the concept of storage is used during each stage. Here are some sentence starters for you :




One useful strategy you can employ when solving computational problems is to think about the output first before you work back to the initialisation. After all, how do we know how to achieve the outcome if we don't know what it is!  Consider the following worked example, Adding up a list of numbers. There is no need to evidence your learning in the first part of this section.


In a script

Open up the Python programming environment and create a new script from 'File > New file'. Save the script in a suitable place in your user area and call it sumOfNumbers.py. Between the following stages, new code is shown in bold type. Comments are shown in red.

Outputs

Decide how the output should look using a specific example. Put this in the # Output section. Run your code to make sure that it works.

# Output
print('Total of all numbers : 29')
Start by deciding on the output

Initialise

Identify and replace the variable values in the output with suitable identifiers. Consider the use of the
.format() method which is more powerful than '+' or comma. Initialise the identifier in the # Initialise section of your script with it's example value. Run your code to make sure that it works.

# Initialise
total = 29


# Output
print('Total of all numbers : {0}'.format(total))
Generalise the output and initial the output variable to mimic the output value

Now reset the initialised value for the identifier to zero. Run your code again to make sure that it works.

# Initialise
total = 0

# Output
print('Total of all numbers : {0}'.format(total))
Now initialise the output to zero

Process

Think about how you will work out the value of the identifier. Write the processing section of your script. If you use any more variables, remember to initialise them in the # Initialise section of the script. Run your script to make sure that it works.

# Initialise
numbers = [13,12,5,66,23]
number = 0
total = 0

# Processing
for number in numbers:
    total = total + number


# Output
print('Total of all numbers : {0}'.format(total))
Now create a fixed case to simulate the processing

Now reset the initialised values for the identifiers to zero / empty in the case of lists. Run your code again to make sure that it works.

# Initialise
numbers = []
number = 0
total = 0


# Processing
for number in numbers:
    total = total + number

# Output
print('Total of all numbers : {0}'.format(total))
... and then reset the case to its initial value

Process

Think about how you will generate values for the identifiers you use in the processing section. Save and run the script to make sure it works. If you are struggling, there is a copy of this available to download called 'sumOfNumbers.py' - remember to save, right click and 'Edit with IDLE' (or your favourite IDE). 

# Initialise
numbers = []
number = 0
total = 0

# Input
finished = False
while not finished:

  number = int(input('Enter number to sum (0 to end) : '))
  if number != 0:
    numbers.append(number)
  else:
    finished = True


# Processing
for number in numbers:
    total = total + number

# Output
print('Total of all numbers : {0}'.format(total))
Finally, generate the values using the input

Click on the picture below which summaries the steps before you attempt the task which follows.

https://drive.google.com/file/d/0B83yXMOilskaTG9WaGhMQzFoWEU/view?usp=drive_web
Click to enlarge


Task 1.2 On its head!
Where you practice developing problem using a bottom-up strategy



In a script

Construct Python scripts for the following situations using the bottom-up method I have just shown you. 
  • Working out the length of a message provided by the user.
  • Working out the total of two numbers added together.
  • Working out the modulus (remainder) when dividing any number by another number.
  • Working out the average of a list of numbers provided by the user.
  • Printing every third letter from a message provided by the user.
  • Challenge : A simple calculator which performs addition, subtraction, multiplication or division on two numbers.
On paper

Print out your scripts using Notepad++ to syntax highlight the code. You will gain credit for having an Initialise section, an Input section, a Processing section and an Output section. Annotate your scripts manually using a pen (that's a stick you write with) to explain what each part of the script does.



In some programming languages, you have to declare (and sometimes initialise with a value) variables before you use them. Python is not like this but it's a very good habit to get into. Specifically, if you are asked to develop a program for your coursework, you will be expected to write a 'variables listing' before you begin development (though most people do this afterwards!)

Activity 2 Abstraction   I   O   A   E 

You might have heard of the work 'abstraction' or more probably the term 'abstract'. Abstraction is either a ...



Task 2.1 Abstraction
Where you learn about the application and benefits of abstraction


Complete the diagram

Copy / sketch the diagram which explains the three different meanings of the term "abstractioninto your notes. 

The London Underground

In 1933, Henry Charles Beck, known as Harry Beck created a highly stylised map of the London Underground System. Rather than drawing his map using the geographical locations of the stations, he took inspiration from the layout of wires on an electrical circuit board, abstracting the map of London to emphasise the connections between the stations rather than their physical locations.

Geographical Map from TFL Website and Standard Tube map from TFL Website

You will be given two maps of the London Underground system - one geographical and one abstracted. Split into pairs each with a different map. Use your map to plan the following routes.
  • Green Park to Ealing Broadway
  • Finchley Road to London Bridge
  • Bethnal Green to Elephant and Castle



In your notebook / on paper

Download a copy of the 'The London Underground' worksheet print yourself a copy. Record the routes you choose in Step 1 and use the 'chatheads' below and the worksheet to help you to discuss the following questions ...
  1. How is Harry Beck's map an example of abstraction and how does it make journey planning easier?

  2. What information has been left off the abstracted map of the London Underground and why?

  3. How might you create different abstractions of the London Underground be different for ...
    - tourists (hint: include tourist attractions)
    - businessmen
    - parents of young children
    - young adults
    - older citizens




Task 2.2 What about programming?
Where you practice application of abstraction in programming and see its benefit


Reading

In programming terms, abstraction makes implementation easier since we do not have to think about implementing every nuance of the solution. Furthermore, abstraction allows us to pattern match existing solutions to new problems meaning that implementations can remain static whilst the careful design of interfaces can link them to any similar context ...

https://drive.google.com/file/d/0B83yXMOilskaOE9ON0NkdlF1WXM/preview
Click to enlarge



Download a script

Download the script 'interfaces.py', save it to a suitable place in your documents and right click and 'edit with IDLE' or your favourite Python editor.

Run the script

Run the script and select an 'interface' from the menu. Follow the instructions to work out the average of 'whatever'. Now look carefully at the script - can you see how the processing is the same no matter which interface you choose?

In your workbook

Print out the script using Notepad++ for your notebooks / folders. Compare the script with this diagram ...


Describe what the script shows - you might find it useful to rubber duck the script with your shoulder partner. Make sure you use the words 'interface' and 'implementation' in your explanation.

Challenge : Come up with your own example for 'adding a list of values' with five difference 'interfaces' and write down your ideas in your workbook.


"Abstraction involved removing unnecessary detail from a problem in order to make it easier to solve"

Activity 3 Decomposition 
  I   O   A   E 

Answer : One byte at a time!

Sometimes, problems are too big to handle all at once. Also, breaking a problem down, or decomposing it, can expose similarities to other problems we have solved in the past which makes implementation easier. However, we do have to be very careful to make sure that the little bits fit back together again!

Fancy a go?


Task 3.1 Haven't we seen this before?
Where you practice decomposition using flowcharts


Yes we have, many times! Whenever we program, we naturally use decomposition to break down the problem from the global 'I want to find the solution to x, y or z' to the individual Initialisation, Input, Processing, Output steps.

In your notebooks / on paper

Look back at the first script that we met in this section ('sumOfNumbers.py') and try to represent this script as a flowchart, maybe using Flowgorithm (though that might be tough!)

Whilst you are designing your flowchart you are forced to use decomposition! As a reminder, here are the flowchart symbols ...


Activity 4 Random number generators  I   O   A   E  

Random numbers are crucial to modelling real life situations. Without random numbers, life would be predictable (and really boring). All programming languages give you tools to generate random numbers - you'll get the chance to practice this with Python in a little while ...


Task 4.1 Randomness
Where you learn about applications of random numbers and how to generate them using Python


Before we learn to how to simulate random events ourselves, how about these!

http://www.mazegenerator.net/  http://www.plot-generator.org.uk/   http://rndimg.com/

In your notebooks / on paper

Print out one of each randomly generated artefact for your notebook / folder. Underneath each one, explain the role of the random numbers generator.

The following steps in this task will help you to learn how Pythons' random number generator can be used.


Random number generator functions

Read the whole of this step first before you start to code. It's set out like a book or online resource might present the operation of code to get you used to the way in which books do this. The words in italics should be replaced with suitable variable names or values.

Before you start using random number generation functions in Python, you must ...

import random

The four most useful random number generator functions are ...

variable = random.random()

... which generates a random decimal number between 0 and 1;

variable = random.randint(start,stop)

... which generates a random integer between start and stop;

variable = random.choice(sequence)

... generates a single value at random from sequence;

You can specify the sequence variable first or include it in the function parameter. If you are going to specify the sequence first, you could use this style of assignment ...

sequence = [item[,item]*]

... where sequence is the variable which holds the sequence (can be a list, tuple or a string) and item is an item in the sequence. The italic square brackets and the asterisk ([,item]*) means that there can be one or more extra items in the sequence. You don't put the square brackets or the asterisk in the command!

The shuffle() procedure shuffles a list in place, so you must create the sequence first before you shuffle it - you can't supply it as a parameter to the function - it makes no sense to!

sequence = [item[,item]*]
random.shuffle(sequence)

There is also a fantastic random number function called sample() which generates a sample of random data from a 'population' ...

sequence = random.sample(population,n)

... where population can be generated from a range() object, e.g. range(1,100)
... where n is the number of values you want from that population, e.g. 10
A reference for the most common random number generation functions

If you are lucky, your teacher might demonstrate these to you as well!

Get ready to code

Open up your favourite Python development environment.

Get ready to document!

Whilst you are working, I would like you to document these five random number generator functions on the 'Random number generator functions' worksheet. Read the instructions carefully before you start.

At the prompt

Before we start, you need to import the random number generator module. Type the following command and press the  ENTER  key.

>>> import random
You must do this before you use any random number functions

At the prompt

Investigate the operation of the four functions and one procedure outlined in Step 1. Document examples of the functions and procedure in operation and remember to replace variablestart, stop and sequence with suitable values. When you have completed the sheet, print it out for assessment - remember to put your name in the header!



What is your favourite random number generator function and why?


Task 4.2 Context, init?
Where you use an abstracted script which generates random numbers and use it in a variety of scenarios


Simply generating a random number means nothing at all - it is without context or meaning! It is simply a number. Before we can truly learn the "power" of the RNG, we need to be able to apply it to real life situations ... 


When it comes to the crunch, most lessons on random number generation focus on ...
  • dice throwing (choosing a random number between 1 and 6);
  • coin flipping (choosing either 'H' or 'T');
  • playing cards (choosing a card at random from a deck of 52)
The playing card situation is complicated slightly by the fact that you need to keep track of which cards you've already chosen from the pack so you don't chose them again ...


Dice throwing

Try typing in these scripts which simulate dice throwing. The first one is designed to generate a fixed number of throws whilst the second one carries on throwing until you want to stop. In both cases, the important line is the one which 'throws' the dice ...

import random

# Initialise
throws = []
number = 0

# Input
number = int(input('How many dice throws : '))

# Process
for i in range(number):
  throw = random.randint(1,6) # Throw dice
  print('You threw a {0}'.format(throw))
  throws.append(throw)

# Output
for i in range(number):
    print('Dice throw {0} : {1}'.format(i+1,throws[i]))
Simulate throwing a dice a fixed number of times

import random

# Initialise
throws = []
finished = False

# Process
while not finished:
  if input('Enter to roll (\'x\' to end) ... ') == 'x':
    finished = True
  else:
    throw = random.randint(1,6) # Throw dice
    print('You threw a {0}'.format(throw))
    
throws.append(throw)

# Output
for i in range(len(throws)):
    print('Dice throw {0} : {1}'.format(i+1,throws[i]))
Simulate throwing a dice until you enter 'x' to stop

Coin flipping

Next, let's look at generating a sequence of random letters which simulate a series of coin tosses.  This time, we need to create a list of choices first and then use the random.choice() function to choose from this list. Again, there are two versions of this - one which generates a fixed length sequence of flips and one which carries on generating a sequence until you want to stop.

import random

# Initialise
faces = ['H','T']
flips = []
number = 0

# Input
number = int(input('How many coin flips : '))

# Process
for i in range(number):
  flip = random.choice(faces) # Flip coin
  print('You flipped a {0}'.format(flip))
 
flips.append(flip)

# Output
for i in range(number):
    print('Coin flip {0} : {1}'.format(i+1,flips[i]))
Simulate flipping a coin a given number of times

import random

# Initialise
faces = ['H','T']
flips = []
finished = False

# Process
while not finished:
  if input('Enter to flip (\'x\' to end) ... ') == 'x':
    finished = True
  else:
    flip = random.choice(faces) # Flip coin
    print('You flipped a {0}'.format(flip))
    flips.append(flip)

# Output
for i in range(len(flips)):
    print('Coin flip {0} : {1}'.format(i+1,flips[i]))
Simulate flipping a coin until you enter 'x' to stop

Playing cards

Lastly, how about a script which chooses a series of playing cards from a deck? This is a little bit more complicated because you need to keep track of which card you have chosen - you can't choose the same card twice. To make things a little easier, I'll only simulate one suit.

import random

# Initialise
deck = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
hand = []
number = 0
finished = False

# Input
number = int(input('How many cards (max 13) : '))

# Process
for i in range(number):
  chosen = False
  while not chosen:
    card = random.choice(deck) # Choose card
    if card not in hand:
       print('You drew a {0}'.format(card))
       hand.append(card)
       chosen = True

# Output
for i in range(number):
    print('Card {0} : {1}'.format(i+1,hand[i]))
Choose a fixed number of playing cards ensuring not to pick the same one twice

import random

# Initialise
deck = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
hand = []
finished = False

# Process
while not finished and (len(hand) < len(deck)):
  if input('Enter to choose card (\'x\' to end) ... ') == 'x':
    finished = True
  else:
    chosen = False
    while not chosen:
      card = random.choice(deck) # Choose card
      if card not in hand:
        print('You drew a {0}'.format(card))
        hand.append(card)
        chosen = True

# Output
for i in range(len(hand)):
    print('Card {0} : {1}'.format(i+1,hand[i]))
Choose a playing card until you enter 'x' ensuring that you don't choose the same card twice or chose more than 13 cards.



Programming challenges

Attempt the following challenges to demonstrate your understanding. Use the repl.it website to submit your code so your teacher can run it, check that it works correctly and give you feedback.

https://repl.it/student
Assignment : CS19 Task 4.2 EASY


Random route through a maze

Using the Random Maze Generator website, generate a simple 10x10 maze. Click the 'Download' button to download yourself a copy of the maze and it's solution and print it out for your notebooks / folders. Now write a Python script which will generate a random route through the maze. The script should
  • ask you how many steps you would like to generate and 
  • should present your random route in the following form ...


... where N means 'North', E means 'East', S means 'South' and W means 'West'.


Now try following your random route through your maze - how many random steps do you think you might need to generate in order to guarantee escaping? Do you think the published maze solution was generated randomly?


https://repl.it/student
Assignment : CS19 Task 4.2 MEDIUM


Random sentence generator

Using the Python random number generator, write a script which will generate a sentence of the general form ...

The [noun_a] [verb] [adverb] towards the [adjective] [noun_b]

... where the words in square brackets are chosen at random from the following sequences ...

nouns = ['puppy', 'car', 'rabbit', 'girl', 'monkey']
verbs = ['runs', 'cycles', 'jumps', 'drives', 'lurches']
adverbs = ['crazily', 'absent-mindedly', 'suspiciously', 'happily', 'foxily']
adjectives = ['adorable', 'clueless', 'dirty', 'odd', 'stupid']

The script should ensure that noun_b (end of the sentence) is *not* the same as noun_a (at the beginning).

For instance ...



https://repl.it/student
Assignment CS19 : Task 4.2 HARD


Random ASCII image generator

Using the Python random number generator, write a script will ask for the side length of the picture and generate a 'square' image like the one shown below using the symbols '<', '>', '/', '\', 'O' and '.' ...




Assessment Task (Homework)


Random number generators can be used to simulate the arrival time of a customer at the till in a supermarket. Come up with 4 more contexts for random number generation and write about them in your notebooks. 

Grading rubric

MASTER : I have come up with 4 completely different contexts that any of the examples that I have been given and discussed how random number generation could be used in a computer model of that situation.
APPRENTICE I have expanded on the use of random number generators in the contexts I have been given.
NOVICE : I have merely paraphrased the examples I have been given.

Click to download revision cards
https://docs.google.com/document/d/1kmFwpJCDPO2-IXKS_NE4p9ei3g3yDtLwZyWkd34e7Lo/export?format=pdf
Remember to print them single sided

# Flash cards.png
Click to load key word list to help you make your own flash cards 

https://goo.gl/forms/F0C0QaNQuLk6pIsq2
Try to get 5/5!


Hungry for more?

There are lots more random number generator goodies available at the famous Random.org website.

How about creating a keyword quiz? Use this template to help you! (You gotta type it in ... soz)




FAQ

Q : "What is initialisation?"
A : This is where you create a variable and assign it an initial value before you use it. Initialisation often occurs at the start of a section of code.

Q : "What other random number generator functions are there?"
A : Look here. There are plenty more but they are probably more than you would need at GCSE level

Q : "What is the difference between a Random Number Generator and a Pseudo Random Number Generator?"
A : Pure Random Number Generators uses natural randomness which exists in nature (weather patterns, cosmic background radiation) to generate random numbers whereas a Pseudo Random Number Generator uses the computers system clock to generate the random number. This can lead to repetition in the random number sequence.

Q : "Why do I need to put 'import random' at the top of my script before I can use the Random Number generator?"
A : There are no built in random number generator functions in the standard Python library so we need to import a new library before we can use them.