Lists, Array, Random
Lists, Array, Random
ARRAYS, LISTS
RANDOM NUMBER GENERATION
CHAPTER 2A.4
VARIABLES AND MEMORY
• In programming languages a variable is used to
hold a particular piece of data. It could be of type
‘string’, ‘Boolean’, ‘integer’ etc. And then
depending on the type of data, a certain amount
of memory will be given to the variable to store
the data. We can consider memory in a computer
system to be like a huge bookshelf with each shelf
being a single memory location. So a ‘Boolean’
variable may require one of these ‘shelves’
whereas a string may need ‘more’.
DATA STRUCTURES - ARRAYS
Some languages however, have ‘List’ data structures. These are known
as ‘Dynamic’ arrays as they enable the grouping of data in programs
with the added advantage of being able to ‘grow’ in size. Behind the
scenes, the ‘List’ structure is in fact a ‘Static’ array. But when the
programmer wishes to add data to the list, if there is no room, the
language will create a new ‘static’ array in another part of memory of
twice the size and copy the data over. Lists therefore do not have to be
declared to begin with and can be appended to. The downside is that in
programs with lots of data, processing times can be longer.
Python doesn’t have arrays – it has lists!
In the boxes you will place the names of the student. The numbers above is the
index.
Notice that the index in Python starts always from 0, while in pseudocode it ups
on you.
HOW CAN YOU CREATE AN 1-DIMENSIONAL LIST
In many cases, you will need to generate a random number (integer or real). In
order to do this, you will need first to import the random library. For instance, if
you want to generate a random integer in range 1 to 10 (now both boundaries
are included), you should type:
import random # you import the library
num = random.randint(1,10)
print(num)
GENERATE A RANDOM REAL NUMBER
On the other hand if you want to generate a random number, you should type:
import random
num = random.rand()
print(num)
By default the range of the random number will be from 0 to 1. if you want to generate
a float number with a different range, then you should use a mathematical function to
achieve this range, for instance if you want to generate a random float number in the
range 5 to 8 then:
import random
decPart = random.rand()
intPart = random.randint(5,8)
num = intPart + decPart
print(num)
CHOOSE A RANDOM ELEMENT OF THE LIST
You can choose a random element from a given list either using the index of the array,
or by using the random function directly into the list. Below you can see both methods.
import random
colors = [‘red’, ‘green’, ‘blue’, ‘orange’]
colorChoice = random.choice(colors)
print(colorChoice)
Or
import random
colors = [‘red’, ‘green’, ‘blue’, ‘orange’]
index = random.randint(0, len(colors)-1)
colorChoice = colors[index]
print(colorChoice)
HOMEWORK