Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python - Objective 08

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Learn how

[Header text] to use arrays and lists Craig’n’Dave


Craig’n’Dave

TRY
Sample program:
# Arrays and Lists

# Function to output the contents of a list


def OutputList(Sentence):
Index = 0
for Word in Sentence:
print("Word {} is {}.".format(Index, Word))
Index = Index + 1

# Main program
Sentence = ["The", "quick", "brown", "fox", "jumps"]
OutputList(Sentence)

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program outputs the contents of a list.

Understand how the code works:


# Arrays and Lists Variables can only contain one value. Sometimes it would be useful if a single identifier
could hold multiple items. E.g. names of students in a class, or in this example, words in a
# Function to output the contents of a list sentence. A list is an alternative to a variable that does this.
def OutputList(Sentence):
Index = 0
for Word in Sentence: • One advantage of using a list is that you can use a loop to
print("Word {} is {}.".format(Index, Word)) iterate through all the items held in it.
Index = Index + 1
• A counting variable called Index is used in this program
# Main program to illustrate how each element of a list also has an index,
Sentence = ["The", "quick", "brown", "fox", "jumps"] just like the characters in a string.
OutputList(Sentence) • In fact, a string is just a list of characters!

• Sentence is declared as a list of strings and enumerated


• You can pass lists as parameters just like variables.
to contain the five words, “The”, “quick”, “brown”,
“fox”, “jumps”.

Did you know that Python is widely reported as supporting only lists and not arrays. However, this isn’t true! A list in Python is an array,
it just behaves more like a list and therefore people mistakenly refer to the data structure as a list with Python. The “list” replicates the
functionality of both arrays and lists and therefore only one structure of this type is needed in Python.
We know this because Python keeps all elements of a list in contiguous memory and moves the entire data structure in memory when
it needs to without the programmer or user knowing. That’s an example of abstraction.

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program outputs the contents of a list.

Understand how the code works:


# Arrays and Lists

# Function to output the contents of a list


def OutputList(Sentence):
for Index in range(len(Sentence)): • This is the same program using a classic for loop instead.
Word = Sentence[Index]
print("Word {} is {}.".format(Index, Word))

# Main program
Sentence = ["The", "quick", "brown", "fox", "jumps"]
OutputList(Sentence)

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

TRY
Sample program:
# Arrays and Lists

# Function to output the contents of a list


def OutputList(Sentence):
for Word in Sentence:
print(Word + " ", end="")
print()

# Main program
Sentence = ["The", "quick", "brown", "fox", "jumps"]
OutputList(Sentence)
Sentence[1] = "small"
Sentence[2] = "grey"
Sentence[3] = "squirrel"
OutputList(Sentence)

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program changes elements and outputs the contents of a list.

Understand how the code works:


# Arrays and Lists

# Function to output the contents of a list


def OutputList(Sentence):
for Word in Sentence:
print(Word + " ", end="") • The words are concatenated with a space so that they are output one after another with a space in
print() between. end="" prevents a new line after each word. The print() outside the loop starts a new line at
the end of the sentence.
# Main program
Sentence = ["The", "quick", "brown", "fox", "jumps"]
OutputList(Sentence)
Sentence[1] = "small"
Sentence[2] = "grey" • Individual elements can be changed by referring to their index.
Sentence[3] = "squirrel" Indexes start at 0.
OutputList(Sentence)

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

TRY
Sample program:
# Arrays and Lists

# Function to output the contents of a list


def OutputList(Sentence):
for Word in Sentence:
print(Word + " ",end="")
print()

# Main program
Sentence = []
for Counter in range(2):
Sentence.append("")

Sentence[0] = "Hello"
Sentence[1] = "World"
OutputList(Sentence)

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program assigns Hello World to two elements of a list.

Understand how the code works:


# Arrays and Lists

# Function to output the contents of a list


def OutputList(Sentence):
for Word in Sentence:
print(Word + " ",end="")
print()

# Main program • It is not necessary to put data into the list when it is created. You can declare an empty list, but it contains
Sentence = [] no indexes at this point.
for Counter in range(2): • You will need to initialise all the elements to something before it will have indexes.
Sentence.append("") • The for loop creates two elements and initialises them to an empty string.
• If Sentence contained numbers instead then you could use Sentence.append(0), but since Python adapts to
Sentence[0] = "Hello" different data structures automatically you don’t need to do this.
Sentence[1] = "World"
OutputList(Sentence)

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

TRY
Sample program:
# Arrays and Lists

Product = [["" for X in range(2)] for Y in range(4)]

# Subroutine to put data into the list


def NewDatabase():
global Product
Product[0][0] = "Cornflakes" ; Product[0][1] = "1.40"
Product[1][0] = "Weetabix" ; Product[1][1] = "1.20"

# Subroutine to output a product from the list


def OutputProduct(Number):
global Product
print("{}: £{}".format(Product[Number][0], Product[Number][1]))

# Main program
NewDatabase()
OutputProduct(1)

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program creates a 2D list, assigns data and outputs one row.

Understand how the code works: • Note this list has been declared outside of all the subroutines.
• This makes it a global data structure. That means all subroutines can use
# Arrays and Lists
global data without passing parameters.
• This program would be a little more efficient because it is not copying the
Product = [["" for X in range(2)] for Y in range(4)]
array when subroutines are called.
• The for loops initialise a list of a list with 4 rows and 2 columns.
# Subroutine to put data into the list
def NewDatabase():
global Product • You can create a table of data using a 2-dimension list.
Product[0][0] = "Cornflakes" ; Product[0][1] = "1.40" • A list can contain any number of dimensions.
Product[1][0] = "Weetabix" ; Product[1][1] = "1.20" • The semi colon allows you to put more than one command in a line of code.
Not generally recommended, but useful here.
# Subroutine to output a product from the list
def OutputProduct(Number):
global Product
print("{}: £{}".format(Product[Number][0], Product[Number][1])) • Data is added to the list. You can visualise it like this:

Product 0 1
# Main program 0 Cornflakes 1.40
NewDatabase() • The list is not passed to the subroutines
OutputProduct(1) because it is a global data structure in 1 Weetabix 1.20
this program. 2
• Note the use of the keyword global in
each subroutine. This is not actually 3
necessary in this program, but some
programs may not work if you don’t
include it.

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

TRY
Sample program:
# Arrays and Lists

Pocket = []

# Subroutine to put data into the list


def PutInPocket(Item):
global Pocket
Pocket.append(Item)

# Subroutine to remove data from the list


def TakeOutOfPocket(Item):
global Pocket
Pocket.remove(Item)

# Subroutine to output the list


def ShowPocket():
global Pocket
for Item in Pocket:
print(Item)

# Main program
PutInPocket("Wallet")
PutInPocket("Keys")
PutInPocket("Tissue")
TakeOutOfPocket("Keys")
ShowPocket()

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE This program adds, removes and outputs items in a list.

Understand how the code works:


# Arrays and Lists
• A new global list is declared called “Pocket”.
Pocket = [] • Lists are dynamic, so they do not have a defined number of elements.

# Subroutine to put data into the list


def PutInPocket(Item):
global Pocket
• .append is a method to add a new element to the list.
Pocket.append(Item)

# Subroutine to remove data from the list


def TakeOutOfPocket(Item):
global Pocket
Pocket.remove(Item) • .remove is a method to remove an element from a list.
• You can do this by index too, but indexes may change as items are added
# Subroutine to output the list and removed from a list because it is dynamic.
def ShowPocket():
global Pocket
for Item in Pocket:
print(Item)

# Main program
PutInPocket("Wallet")
PutInPocket("Keys")
PutInPocket("Tissue")
TakeOutOfPocket("Keys")
ShowPocket()

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Learning points from this objective:
• An array is an identifier that holds more than one item of data of the same data type. In Python a list can contain data from different data types.
• Arrays are static data structures because the size of the array in memory cannot change when a program is executing.
• The item of data that an array or list holds is called an element.
• Each element is numbered with an index, starting with the first element at index 0.
• In python arrays and lists are the same type of data structure. You only need to understand the difference for exams.
• A list is a dynamic data structure because its size can change when the program is executing. That is because dynamic data structures are not held in contiguous
memory, each element contains a pointer to the next element in the structure that the programmer cannot see because it is abstracted. New elements can
easily be added and removed by changing the pointers. Lists are sometimes called linked lists too.
• The advantage of using an array or list instead of multiple variables is that you can use an iteration to loop through the elements it contains by using the index.
• If arrays or lists are given data that can never change in the program, like a constant, it is said to be immutable. If the data changes it is mutable.
• Enumeration is initialising data into an array or list when it is declared.
• Lists have many built-in methods that can be applied to them. A built-in method is just an algorithm that the programmer cannot see the code for.
• It may be easier to visualise an array and a list like this:

Array List

Identifier: Sentence Sentence


Index: 0 1 2 3 4 0 The 1 quick 2 brown 3 fox 4 jumps
Element: The quick brown fox jumps

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Learning points from this objective:
• Arrays and lists are just an abstraction of memory. You can visualise 2D lists as either being [row, column] or [column, row], it doesn’t matter.
• Global data structures are available to all subroutines. They have a fixed memory footprint that does not change when the program is executing. That makes
them generally more CPU efficient (because data is not copied in memory), but less memory efficient (because the program doesn’t release the memory when
the data structure is not being used).
• Local data structures are only available to the subroutine they are declared in. Passing parameters is necessary to share local data between subroutines. That
makes them generally less CPU efficient, but more memory efficient.
• You should only use global data structures for data that is used very frequently by many subroutines. It is considered good practice to use local data structures
as much as possible. They allow the operating system to manage the memory better, reducing the need for virtual memory. They also create more isolated and
reusable program components.

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Program comprehension: ITEM Identify a local data structure.

1. import random

2. Grid = [["" for X in range(5)] for Y in range(5)] Identify a global data structure.

3. def NewGrid():
4. random.seed()
5. for Y in range(5):
Identify a nested iteration.
6. for X in range(5):
7. ASCII = random.randint(1,26) + 64
8. Letter = chr(ASCII)
9. Grid[X][Y] = Letter

10.NewGrid() PURPOSE What do lines 7 and 8 together achieve?

What does the subroutine NewGrid do?

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Why does line 2 require two for loops, why can’t Grid simply be
Program comprehension: REASON
declared like this: Grid[[]] ?
1. import random

2. Grid = [["" for X in range(5)] for Y in range(5)]


Why is + 64 needed in line 7?
3. def NewGrid():
4. random.seed()
5. for Y in range(5):
6. for X in range(5):
7. ASCII = random.randint(1,26) + 64
8. Letter = chr(ASCII)
9. Grid[X][Y] = Letter

10.NewGrid()

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Keywords introduced in this objective:
X = ["e1", "e2"] Declares and enumerates a one-dimension list of strings.
Any data type can be used in the declaration with the correct qualifiers for the data inside the
squared brackets.
Lists can be passed into subroutines as paramters.
X = [] Declares an empty list.
Or… Data can be added to empty lists with the .append method, but a data cannot be added using
X = list() indexes until the elements are initialised.
X = ["" for Y in range(Z)] Initialises Z elements of list X.

X[Y] = "Z" The element at index Y of array X is assigned to be Z.


Remember to use the correct data type qualifiers for Z.
X = [["" for Y in range(Z)] for V in range(W)] Declares a two-dimensional list X of strings with Z x W indexes.
W and Z can be thought of as rows and columns, but this is an abstraction and there is no explicit
instruction for W to be rows and Z to be columns. It can work either way.
X[Y][Z] = "W"; The element at index Y, Z of list X is assigned to be W.
Remember to use the correct data type qualifiers for Z.
global Used inside a subroutine to specify a data structure used within the subroutine is the global data
structure.

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

INVESTIGATE
Keywords introduced in this objective:
X.append(Y) Adds Y to list X.

X.remove(Y) Removes Y from list X.

X in Y Returns True if X is contained in list Y.


E.g. if X in Y:
X.pop(Y) Removes the element at index Y from list X.
This will also decrement the indexes of elements after Y.
X.insert(Y,Z) Inserts element Z at index Y in list X.

X.sort() Sorts all the items in list X. Never use this as an answer to an exam question about sorting data in
a data structure. You need to show what the .sort method is doing to the data!
X.extend(Y) Appends list Y to list X.

X.reverse() Reverses the order of items in list X.

del X[:] Removes all items from a list.

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

MAKE # Quote of the day problem


import random

Quote of the day problem: # Function to output a random quote


def RandomQuote():
1 point.
Write a program that will output a random Quote[1][0] = "Code is like humour. When you have to
quote and who said it. The quotes and authors explain it, it’s bad."
should be stored in a 2D array.
Quote[1][1] = "Cory House"

Quote[0][0] = "Any fool can write code that a computer can


understand. Good programmers write code that humans can
understand."
Quote[0][1] = "Martin Fowler"

Quote[2][0] = "Simplicity is the soul of efficiency."


Quote[2][1] = "Austin Freeman"

# Initialise data
Quote = [["" for X in range(2)] for Y in range(3)]

return Quote[Index][0], Quote[Index][1]

Quote, Author = RandomQuote()

# Pick a random quote


Index = random.randint(0,2)
To help you get started,
# Main program
here is all the code you
random.seed()
need with the
statements jumbled up.
print("{} - {}".format(Quote, Author)) PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

MAKE
RPG inventory problem:
1 point.
Write a program that will hold the inventory a player has in an RPG game. The player has the following actions: pick (adds an item to the
inventory), drop (removes an item from the inventory), pull (outputs a random item from the inventory) and search (outputs all the items
in the inventory).

Notebook problem:
1 point.
Write a program that allows the user to store up to 10 notes. The program should have this functionality on an infinite loop:
• Output all the notes stored, numbered 0-9.
• Ask the user to enter a number for a note to change.
• Ask the user to enter the new note.
• Over-write any existing note stored at that position.

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

MAKE
Proc gen problem:
2 points.
Procedural generation is a popular technique in games design made famous by the 1984 game Elite, where planets in a galaxy and
creatures inhabiting those planets were generated using a deterministic algorithm.
Write a function that outputs a description of fictional animals that live on a planet. The function takes the number of the planet as an
integer parameter and uses this as a seed for a random number generator so that the same creatures always live on the same planet!
Data might include, but is not limited to:
Creatures: lizards, humanoids, insects
Colours: red, green, blue
Characteristics: shy, angry, docile
An example of an output for a planet might be: “Angry blue humanoids”.
It is important that the outcome is not truly random so that if planet 1652 contains angry blue humanoids, next time it is checked they are
still living there and haven’t been replaced by docile red lizards!

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

MAKE
Underground problem:
2 points.
Each line on the London underground has several stations. The Victoria line has these stations in the following order: Brixton, Stockwell,
Vauxhall, Pimlico, Victoria, Green Park, Oxford Circus, Warren Street, Euston, King's Cross, Highbury & Islington, Finsbury Park, Seven
Sisters, Tottenham Hale, Blackhorse Road and Walthamstow Central.
Write a program that allows the user to input two stations. A function should return the number of stops between the two stations. The
station names can be input in any order, but you can make the problem easier by only inputting stations in the correct order if you need to.

Days of Christmas problem:


2 points.
Write a program that outputs the lyrics from the song, “Twelve days of Christmas” using a nested iteration and arrays for storing the name
of the day i.e. “first”, “second” and the item. E.g. “Two turtle doves”.
On the first day of Christmas
My true love gave to me
A partridge in a pear tree

On the second day of Christmas


My true love gave to me
Two turtle doves
And a partridge in a pear tree

On the third day of Christmas


My true love gave to me
Three French hens
Two turtle doves
And a partridge in a pear tree PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

MAKE
Maths test problem:
3 points.
Write a program that generates a short test of the addition of two-digit numbers. The test contains five questions. The child taking the
test enters their name at the start of the test. The program stores the name of the child and their score out of five. It resets the test at the
end, ready for the next child who will see the same questions.
The names and scores are output before the next test starts.

Tanks problem:
3 points.
Tanks is a game for one player. At the start of the game, the computer places 10 tanks on an 8x8 board but does not reveal their
locations to the player. Each tank occupies one square on the board. The player enters a grid reference, e.g. 1,5 on each turn. The player
destroys the tank if the square is occupied by a tank. The player wins if they destroy all the tanks within 50 turns.
A visualisation of the tanks on the board for one player:
0 1 2 3 4 5 6 7
Write a program to play the game.
0
1 T T T
2 T T
3 T
4
5 T T
6
7 T T PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

MAKE
Strong numbers problem:
3 points.
A strong number is a number whose sum of the factorial of digits is equal to the original number.
E.g. 145 is strong number because 1! + 4! + 5! = 145.
That is: (1*1) + (4*3*2*1) + (5*4*3*2*1) = 145
Write a program that allows the user to enter an integer. The program outputs whether the number is strong or not and ensures that an
arithmetic overflow cannot crash the program.

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

EVALUATE
Test tables:
Problem: Underground

Input 1 Input 2 Expected output Pass/Fail Test

Problem: Strong numbers

Input 1 Expected output Pass/Fail Test

PYTHON T I M E
Learn how
[Header text] to use arrays and lists Craig’n’Dave
Craig’n’Dave

EVALUATE
Review your solutions:
Did you: Self-assess: Yes/No

Complete all the requirements for the problems you solved?

Start your programs with a comment to describe what they do?

Use a subroutine for the main algorithm in your code?

Use a comment to describe what the subroutine does?

Use a comment after each program branch to explain the purpose of the section?

Use a comment before each iteration to explain the purpose of the loop?

Use variable names that describe the data they hold?

Validate or sanitise the user inputs?

Test your programs against different types of data to check they work?

PYTHON T I M E

You might also like