Computer Science
Computer Science
💡 “You can’t just show up here and give yourself random powers. There’s no plot build-up!
Fans will hate us for this.”
Syllabus
a data type based on an existing data type or other data types that have been defined by a
programmer
Pros
Programmer needs specify a new data type that meets the requirement of the
program
Cons
Computer Science 1
Only possible if a programming language offers support for the construct
a single data type that does not reference any other data type
A non-composite data type defined by a given list of all possible values that has an
implied order
A list of prescribed values are created for this user-defined data type, which is defined
by the user
An object of that data type can then be declared and assigned one of those prescribed
values
Much in the same way an INTEGER data type must be a number from 0 to the
largest recognised by the language
A non-composite data type that uses the memory address of where the data is stored
Need to have information about the type of data that will be stored in memory location
The pointer has to relate to the type of the variable that is being pointed to
Pros
Cons
Not all programming languages offer support for the use of PDT
Computer Science 2
Set Data Type
Allows a program to create sets and to apply the mathematical operations defined in
set theory
Allow programmer to create record data type with components that precisely match
the data requirements of the particular program
Choose and design an appropriate user-defined data type for a given problem
TYPE
TDirections = (North, East, South, West)
TDays = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday )
DECLARE Direction1 : TDirections
DECLARE StartDay ← North
StartDay ← Wednesday
DECLARE Weekend : Boolean
DECLARE Day : TDays
Weekend = TRUE OF Day > Friday
ENDTYPE
Computer Science 3
data of all types is stored as records in files
Show Understanding of the methods of file organisation and select an appropriate method of
file organisation and file access for a given problem
records of data are physically stored in a file, one after another, in the order they were
added to the file
Used for temporary files storing transactions to be made to more permanent files
records of data are physically stored in a File, one after another, in a given order
Order is usually based on the ket field of the records as this is a unique identifier
e.g. file used by supplier to store customer records, all records are stored in
ascending customer number order, where the customer number is the key
field that uniquely identifies each record
Has to be key field for which the values are unique and sequential
Append the record, with the intention of sorting the file later
The location of any record in the file is found by using a hash table/hashing
algorithm on the key field of a record
Hash Table = table of data which is ordered not by the key field, but by the
value of the key field
Hence, data can be directly accessed by hashing the key field, rather than
having to look through each record one by one
Computer Science 4
Hashing Algorithm = a mathematical formula used to perform a calculation on
the key field of the record, the result of the calculation gives the address
where the record should be found
chooses a suitable number and divides this number by the value in the
key field
File Access
After file organisation has been chosen, data been entered into a file
Sequential Access
Each record in the file is read, one by one, until the desired record is found
Serial File = if a particular record is being searched for, every record need to be
checked until that record is found or the whole file has been searchers and that record
has not been found
Sequential File = if a particular record is being searched for, every record needs to be
checked until the record is found or the key field of the current record being checked is
greater than the key field of the record being searched for
The rest of the file doesn’t need to be searched as the records are sorted on
ascending key field values
Any new records to be stored are inserted in the correct place in the file
Direct Access
Sequential File = an index of all the key fields is kept and used to look up the address
of the file location where a given record is stored
For large files, searching the index takes less time than searching the whole file
Random Access File = a hashing algorithm is used on the key field to calculate the
address of the file location where a given record is stored
Computer Science 5
Show understanding of hashing algorithm
a mathematical formula used to perform a calculation on the key field of the record, the
result of the calculation gives the address where the record should be found
Write a record
chooses a suitable number and divides this number by the value in the key field
Remainder from this division then identifies the address in the file for storage of the
record
Suitable numbers: prime numbers of a similar size to the expected size of the file
the address of the location to read from is calculated using the hashing algorithm and
the key field of the record stored there is read
But before using that record, the key field must be checked against the original key
field to ensure that they match
If key fields does not match, then the following records needs to be read until a
match is found (open hash) or the overflow area needs to be searched for a match
(closed hash)
A binary number written in the form M x 2^E (where M is the Mantissa and E is the
exponent)
the exponent = the power of 2 that the mantissa (fractional part) is raised to in a
floating-point number
Computer Science 6
Convert binary floating-point into denary and vice versa
Computer Science 7
Computer Science 8
Computer Science 9
Computer Science 10
Normalise floating-point numbers
Computer Science 11
A method to improve the precision of binary floating-point numbers: positive numbers
should be in the format 0.1 and negative numbers in the format 1.0
Positive Number
The bits in Mantissa are shifted to the left until we arrive at 0.1; for each left, the
exponent is reduced by 1
Negative Number
The bis in the mantissa are shifted until we arrive at 1.0; again, the exponent must be
changed to reflect the number of shifts
The accuracy of a number can be increased by increasing the number of bits used in the
Mantissa
Computer Science 12
The range of numbers can be increased by increasing the number of bits used in the
exponent
Accuracy and range will always be a trade-off between Mantissa and Exponent size
Computer Science 13
Show understanding that binary representation can give rise to rounding errors
Overflow Error
If a calculation produces a number which exceeds the maximum possible value that
can be stored in the Mantissa and Exponent, an Overflow error will be produced
This could occur when trying to divide by a very small number or even 0
Underflow Error
When dividing by a very large number this can lead to a result which is less than the
smallest number that can be stored
One of the issues of suing normalised binary floating-point numbers is the inability to store
the number 0
Computer Science 14
This is because the Mantissa must be 0.1 or 1.0 which does not allow for a 0 value
a set of rules governing communication across a network: the rules are agreed by both sender
and recipient
all data is sent and received using the same rules and format
Show understanding of how protocol implementation can be viewed as a stack, where each
layer has its own functionality
The layers are numbered and sit one above each other, and can therefore be thought
of as a stack
The output from one layer provides the input for the next layer
Each layer interacts only with the layer directly above/below it, and at the bottom of
the stack
The Physical layer transmit data between the source and destination devices
uses a set of protocols for transmission of data transport control protocol with internet
protocol
TCP
IP
Computer Science 15
Establish and maintain a connection until exchange of data is complete
4 layer structure
Application Layer
Transport Layer
Check packet destination so the packet can be sent to the correct application
TCP
Internet/Network Layer
IP
Application
Computer Science 16
2. A router is used to transmit packets of data (APP)
3. Host ‘X’ will send host ‘Y’ a packet which will include synchronisation sequence
bits to that segments will be received in the correct order (TR)
4. Host ‘Y’ will now respond by sending back its own packet (containing an
acknowledgment together with its own synchronisation sequence bits) (TR)
5. Host ‘X’ sends out its own acknowledgment that the packet from ‘Y’ was received
(TR)
6. Transmission of data between ‘X’ and ‘Y’ can now take place (TR)
9. Take a packet from the transport layer and add its own header which will include
the IP address of both sender and recipient (DL)
10. The IP packet (datagram) is sent to the data-link layer where it assembles the
data grams into frames for transmission (DL)
Show understanding of protocols (HTTP, FTP, POP3, IMAP, SMTP, BitTorrent) and their
purposes
browsing websites
Pull protocol = client periodically connects to a server; checks for and downloads new
emails from the server, the connection is then closed, this process is repeated to
Computer Science 17
ensure the client is updated
When emails are downloaded by the client, they are then deleted from the server
Push Protocol = a client opens a connection to a server and keeps the connection
active all the time, the client then uploads a new email to their server
BitTorrent
keywords
Tracker
Central server that stores details of other computers that have the file to be
downloaded
Seed
Swarm
Computer Science 18
All the connected peer computers that have all or part of the file to be
uploaded to the torrent
Steps:
3. the torrent is split into small pieces which are given priority in downloading
4. a computer joins by using Bit Torrent software to load the torrent descriptor
6. Once a computer has a piece of the file, it can become a seed and upload it to the
other members
E.g. public telephone networks, private telephone networks, private data networks
Features
A circuit is established at the start of the communication between sender and receiver
Pros
A dedicated channel
Cons
Computer Science 19
Features
A circuit that does not have to be established at the start of the communication
Steps
1. A large message is divided up into a group of smaller chunks of the same size called
packets
4. Each packet is dispatched independently and may travel along different routes
5. The packets may arrive out of order and are reassembled into the original message at
the destination
Pros
Cons
the protocols for packet switching can be more complex than those for circuit
switching
Comparison
Computer Science 20
15| Hardware and Virtual Machines
Processors, Parallel Processing, and Virtual Machines
Reduced Instruction Set Computer (RISC)
a single instruction can be more complex and involve more loading of data from memory
RISC vs CISC
longer execution time for instruction faster execution time for instructions
it is more difficult to make pipelining work easier to make pipelining is on the software
the design emphasis is on the hardware the design emphasis is on the software
Pipelining
Computer Science 21
allows several instructions to be processed simultaneously without having to wait for
previous instructions to finish
Stages
Each stage requires one clock cycle and an instruction passes through the stages
sequentially
Importance
Without pipelining, a new instruction is fetched in stage 1 only after the previous
instruction finishes at stage 5, therefore the number of clock cycle it takes to execute
an instruction is 5
Since one could theoretically have 5 instructions in the 5 pipeline stages at once
(one instruction per stage), a different instruction would complete stage 5 in every
clock cycle and on average the number of clock cycles it takes to execute an
instruction is 1
Interrupt Handling
The usual way to deal this is to discard all instructions in the pipeline except for the last
instruction in the Write-Back (WB) stage
Methods
1. Interrupt handler routine can then be applied to this remaining instruction and, once
serviced, the processor can restart with the next instruction in the sequence
This allows all current data to be stored, allowing the processor to restored to its
previous status once the interrupt has been serviced
Parallel Processing
Computer Science 22
uses a single processor and one data source
Each processor executes the same instructions but use different data inputs
Computer Science 23
uses many processors but the same shared data source
Each processor uses different instructions but uses the same shared data source
Each one can take its instructions independently, and each processor can use data
from a separate data source
The processor from each computer forms part of a larger pseudo-parallel system which
can act like a supercomputer
By linking computers (processors) together in this way, it increases the processing power
of the ‘single machine’
Each processor will carry out part of the processing and communication between
computers is achieved via interconnected data pathways
Virtual Machines
Computer Science 24
this is the OS running in a virtual machine
Benefits
Computer Science 25
Guest OS hosted on a virtual machine can be used without impacting anything
outside the virtual machine
Any other virtual machines and host computer are protected by the virtual
machine software
Useful to test a new OS or new app since they will not crash host computer if
something goes wrong
Possible to run apps which are not compatible with the host computer/OS by using
a guest OS which is compatible with the app
Can emulate the old software on the new system by running a compatible guest
OS as a virtual machine
Limitations
Do not get the same performance running as a guest OS as you do when running
the original system
Building an in-house virtual machine can be quite expensive for a large company
Computer Science 26
Full Adder Circuit
two half adders combined to allow the sum of several binary bits
Sequential Circuits = the output depends on the input value produced from a previous
output value
Flip-flop circuits = electronic circuits with 2 stable conditions using sequential circuits
SR flip-flops
Issues:
If inputs do not arrive at the same time, the flip-flop can become unstable
JK flip-flops
To overcome SR issues:
A clock and additional gates are added which helps synchronise the 2 inputs
Computer Science 27
Hence give 4 possible input conditions: 1, 0, no change, toggle (takes care of
the invalid S and R states)
Use of JK flip-flops:
SR flip-flop
Computer Science 28
JK flip-flop
Computer Science 29
Show understanding of Boolean Algebra
a form of algebra linked to logic circuits and is based on 2 statements: TRUE (1) and
FALSE (0)
Computer Science 30
Simplify a logic circuit/expression using Boolean Algebra
Computer Science 31
Karnaugh Maps (K-Maps)
Computer Science 32
Understand of the benefits of using Karnaugh maps
a method used to simplify logic statements and logic circuits - uses Gray codes
Gray Codes = ordering of binary numbers such that successive numbers differ
by 1 bit value only
Computer Science 33
Computer Science 34
Computer Science 35
16| System Software
Purposes of an Operating System
Understanding of OS
When a computer is first switched on, the Basic Input/Output System (BIOS) starts off a
bootstrap program
Bootstrap = a small program that is used to load other programs to ‘start up’ a computer
Computer Science 36
The bootstrap program loads part of the OS into main memory (RAM) from the hard
disk/SSD and initiates the start up procedures
Process is less obvious in tablets and mobile phones - they uses RAM, but their internal
memory is supplied by flash memory
OS can only be updates by manufacturer but the user cannot interfere with the
software from the memory
CPU
involves the concept of scheduling to allow for better utilisation of CPU time and
resources
Memory
Any I/O operation which has been initiated by the computer user
Any I/O operation which occurs while software is being run and resources, such as
printers or disk drivers, are requested
Direct Memory Access (DMA) controller is needed to allow hardware to access the main
memory independently of the CPU
CPU carries out other tasks while this data transfer operation is taking place
Once the data transfer is complete, an interrupt signal is sent to the CPU from DMA
Computer Science 37
Describe the ways in which the user interface hides the complexities of the hardware from the
user
Kernel
Computer Science 38
Important task: hide the complexities of the hardware from the users
Simplifying the saving and retrieving of data from memory and storage devices
Carrying out background utilities, such as virus scanning which the user can ‘leave
to its own devices’
Multitasking
Ensures the best use of computer resources by monitoring the state of each
process
It should give the appearance that many processes are being carried out at
the same time
2 Types:
Preemptive
Non-preemptive
Comparison
Computer Science 39
Process
Resource equipments (which resources does the process require and how
many)
Turnaround time, waiting time, and response time for the process
Once the task/process has been given priority, it can still be affected by:
data structure which contains all the data needed for a process to run
Process States:
The link
Computer Science 40
Conditions
The need for scheduling and the function and benefits of different scheduling routines
(including round robin, shortest job first, first come first served, shortest remaining time)
Round Robin
scheduling algorithm that uses time slices assigned to each process in a job
queue
Once a process is executed during its time slice, it is removed and placed in the
blocked queue; then another process from the ready queue is executed in its own
time slice
Computer Science 41
The ready queue is worked out by giving each process its time slice in the correct
order
if a process completes before the end of its time slice, then the next process is
brought into the ready queue for its time slice
similar concept of a queue structure which uses First In First Out (FIFO) principle
the data added to a queue first is the data leaves the queue first
Computer Science 42
Shortest Job First
Non-preemptive
Burst time of a process should be known in advance; although this is not always
possible
Preemptive
Computer Science 43
How the kernel of the OS acts as an interrupt handler and how interrupt handling is used
to manage low-level scheduling
Keywords:
Kernel
Steps:
1. Interrupt received; other interrupts are then disabled so that the process that deals
with the interrupt cannot itself be interrupted
b. A process is suspended only if its interrupt priority level is greater than that of
the current task
Computer Science 44
c. The process with the lower IPL is saved in the interrupt register and is handled
(serviced) when the IPL value falls to a certain level
a. The kernel will save the state of the interrupt process on the kernel stack and
the process state will be restored once the interrupting task is serviced
Device interrupt
Exceptions
Traps/software interrupt
4. The system now jumps to the Interrupt service routine (Interrupt Dispatch Table
(IDT))
a. IDT will supply the address of the low level routine to handle the interrupt
event received
5. Once completed, the state of the interrupt task/process is restored using the
values saved on the kernel stack: the process then continues
6. After an interrupt has been handled, the interrupt needs to be restored so that any
further interrupts can be dealt with
Paging
Virtual Memory
type of paging that gives the illusion of unlimited memory being valuable
Benefits:
programs can be larger than physical memory and can still be executed
Computer Science 45
No waste of memory with data that is not being used (e.g. during error
handling)
Drawbacks:
as main memory fills, more and more data/pages need to be swapped in and
out of virtual memory
Segmentation
Computer Science 46
Occurs when a requested pagi is not in memory (P flag=0)
When paging in/out from memory, it is necessary to consider how the computer can
decide which page(s) to replace to allow the requested page to be loaded
When a new page is requested but is not in memory, a page fault occurs and the OS
replaces one of the existing pages with new page(s)
Methods:
How to decide which page to replace is done in a number of different ways, but all
methods have the same goal of minimizing the number of page faults
The oldest page is at the front of the queue and is the first to be removed
when a new page needs to be added
Do not consider page usage when replacing pages: a page may be replaced
simply because it arrived earlier than another page
looks forward in time to see which frame it can replace in the event of a page
fault
the page which has not been used for the longest time is replaced
It is necessary to maintain a linked list of all pages in memory with the most
recently used page at the front and the least recently used page at the rear
Computer Science 47
use a circular queue structure with a single pointer serving as both head and
tail
If R=0, the next page is looked at and this is repeated until a page where
R=0 is found
When a page fault occurs, the OS has to decide which page to remove from
memory to make room for a new page
If more time is spent on moving pages in and out of memory than actually doing any
processing, then the processing speed of the computer will be reduced
A point can be reached when the execution of a process comes to a halt since the
system is so busy paging in and out of memory (thrash point)
Due to large numbers of had movements, this can also lead to premature failure of a
hard disk drive
Translation Software
Show understanding of how an interpreter can execute programs without producing a
translated version
Interpreter
Computer Science 48
There may also be other inputs that the program requires or to correct errors in the
source program
No object code is output, but error messages from the interpreter are output, as well
as any outputs produced by the program being interpreted
Since there’s no object code produced, the interpreter will need to be used every
time the program is executed
Will allocate space in memory to store any constants, variables, and other data items
used by the program
Checks each statement individually and reports any errors, which can be corrected
before the statement is executed
After each statement is executed, control is returned to the interpreter so the next
statement can be checked before execution
Compiler
The program source code is input and either the object code program or error
messages are output
The object code produced can then be executed without needing recompilation
Lexical Analysis
Compiler will use a keyword table that contains all of the tokens for the reserved
words and symbols used in a programming language
Syntax Analysis
The complete tokenized list is checked for errors using grammatical rules for the
programming language (parsing)
The whole program goes through this process even if errors are found
Computer Science 49
Parsing can be set out in Backus-Naur Form (BNF) notation
If any errors are found, each statement and the associated error are output but, in the
next stage of compilation, code generation will not be attempted
If the tokenized code is error free, it will be passed to the next stage of compilation,
generating the object code
Code Generation
This stage produces an object program to perform the task defined in the source code
The use of relocate low code so the program can be stored anywhere in main
memory
Addition of library routines to the code to minimize the size of the stored object
program
Optimization
Optimized programs should perform the task using the minimum amount of resources
(time, storage space, memory, and CPU use
Some optimization can take place after the syntax analysis or as part of code
generation
Not every compiler is able to optimize the object code produced for every source
program
Computer Science 50
Show understanding of how the grammar of a language can be expressed using syntax
diagrams or Backus-Naur Form (BNF) notation
Show understanding of how Reverse Polish Notation (RPN) can be used to carry out the
evaluation of expressions
The values are added to the stack in turn going from left to right
Computer Science 51
When an operator is encountered, it is not added to the stack but used to operate on the
top 2 values of the stack - which is pooped off the stack, operated on, then the result is
pushed back on the stack
This is repeated until there is a single value on the stack and the end of the expression
has been reached
17| Security
Encryption, Encryption Protocols, and Digital Certificates
Show understanding of how encryption works
Including the use of public key, private key, plain text, cipher text, encryption, symmetric
key cryptography, and asymmetric key cryptography
Keywords:
Encryption
securing digital data using one or more mathematical techniques, along with a
password or "key" used to decrypt the information
Computer Science 52
Public Key
two keys are used one key is used for encryption and another key is used for
decryption
One key (public key) is used for encrypt the plain text to convert it into cipher
text and another key (private key) is used by receiver to decrypt the cipher text
to read the message
Available to everyone
Asymmetric encryption
Private Key
Asymmetric encryption
encryption in which the same secret key is used to encrypt and decrypt
messages
Steps:
Both senders and recipient end up with the same encryption and
decryption key of 9
Benefits:
Computer Science 53
Drawbacks
Once compromised the key an be used to decrypt both sent and received
messages
encryption that uses matching pair of keys: public key (known to everyone)
and private keys (secret keys)
Receiver’s public key used for encrypting the messages before it is sent
Receiver’s private key for decrypting the messages agent it has been received
Steps:
3. Sender now uses recipient’s public key to encrypt the document sender
want to send
4. Recipient uses her matching private key to unlock Sender’s document and
decrypt it
This works because the public key used to encrypt the document and
the private key used to decrypt it are a matching pair generated on
Recipient’s computer
Benefits
Allows non-repudiation
Detects tampering
Drawbacks
Computer Science 54
Why do we need encryption?
Minimise risk when data is transmitted over any public network (wired or wireless),
there is a risk of it being intercepted by an eavesdropper
Encryption alters data into a form that is unreadable by anybody for whom the
data is not intended
Cannot prevent data being intercepted, but it stops it from making any sense to
the eavesdropper
Authenticity = the need to identify who sent the data and verify that the source
is legitimate
Integrity = the data should reach its destination without any changes
Non-repudiation = that neither the sender nor the recipient should be able to
deny that they were part of the data transmission which just took place
Quantum Cryptography
Purpose
helps protect the security of data being transmitted over fibre optic cables
Benefits
Drawbacks
Computer Science 55
Requires a dedicated line and specialist hardware, which can be expensive to
implement initially
It still has a limited range (at the time of writing the limit is about 250km)
Show awareness of the Secure Socket Layer (SSL) / Transport Layer Security (TLS)
SSL
when user logs onto a website, SSL encrypt data - only the client’s computer and
the web server are able to make sense of what is being transmitted
A user will know if SSL is being applied when they see the https protocol
and/or the small. green closed padlock
TLS
provides encryption
It ensures the security and privacy of data between devices and users when
communicating over a network (such as the internet)
When a website and client communicate over the internet, TLS prevent a third
party
SSL
TCP is used to established a connection between the client and the server
Computer Science 56
One part of the SSL protocol is to agree which encryption algorithm are to be
used; this is essential to ensure a secure, encrypted communication takes place
TLS
Formed of 2 layers:
Handshake Protocol
The shared session key provides symmetric cryptography for sending and
receiving data (record layer)
Record Protocol
SSL
only the most recent web browsers support both SSL and TLS, which is why the
older, less secure, SSL is still used
TLS
VPN
VOIP
TLS can make use of session catching which improves the overall performance of
the communication when compared to SSL
TLS separate the handshaking process from the record protocol (layer) where all
the data is held
Keywords:
Computer Science 57
Digital Certificate
Digital Signatures
electronic way of validating the authenticity of digital documents (that is, making
sure that have not been tampered with during transmission) and also proof that a
document was sent by a known user
Similarities Differences
Both used for Certificate obtained from issuing authority | Signature created from a
authentication message
Both are unique to the Certificate provides authentication of owner | Signature used to
owner/subject authenticate messages that are sent by owner
Name, address
Then the message digest/hash total is encrypted with owner’s private key
How asymmetric encryption uses the contents of DC to ensure the message has not been
altered
B’s Message is encrypted using A’s public key (provided by the DC)
The message digest is then encrypted with B’s private key to provide a DS
B’s DS is decrypted with B’s public key to obtained the message digest
B’s hashing algorithm recreates the message digest from the decrypted message
The 2 message digests are compared, if same then message has not been altered
Computer Science 58
18| Artificial Intelligence (AI)
Show understanding of how graphs can be used to aid Artificial Intelligence (AI)
Artificial Intelligence
Dijkstra’s Algorithm
Steps:
2. Give each vertex connected to the vertex we have just given a final value to a
working (temporary) value
3. Check the working value of any vertex that has not yet been assigned a final
value
Assign the smallest value to the vertex ; this is now its final value
4. Repeat steps 2 and 3 until the end vertex is reached, and all vertices have
been assigned a final value
5. Trace the route back from the end vertex to the start vertex to find the shortest
path between these 2 vertices
A*
An algorithm that finds the shortest route between nodes or vertices but uses an
additional heuristic approach to achieve better performance than Dijkstra’s
algorithm
Steps:
1.
Computer Science 59
Show understanding of how artificial neural networks have helped with machine learning
Neural Networks = an algorithm loosely inspired by the brain, have revolutionized many
fields, including computer vision
Computer Science 60
Computer Science 61
Show understanding of Deep Learning, Machine Learning, and Reinforcement Learning and
the reasons for using these methods
Machine Learning
A computer program that improves its performance at certain tasks with experience
Supervised Learning
Using known tasks with given outcomes to enable a computer program to improve
its performance in accomplishing similar tasks
Computer Science 62
Classification
Regression
Unsupervised Learning
Using a large number number of tasks with unknown outcomes and the use of
feedback to enable a computer program to improve its performance in
accomplishing similar tasks
Computer Science 63
Deep Learning
Reinforcement Learning
Using a large number of tasks with unknown outcomes and the use of feedback to
enable a computer program to improve its performance in accomplishing similar tasks
Computer Science 64
Learn to pick an action based on the state of the world, and “rewards” or
“punishments” from previous choices
Back Propagation
method used in artificial neural networks to calculate error gradients so that actual
node/neuron weighting can be adjusted to improve performance of the model
Steps:
The initial outputs form the system are compared to the expected outputs and the
system weightings are adjusted to minimise the difference between actual and
expected results
Calculus is used to find the error gradient in the obtained outputs: the results are
fed back into the neural networks and the weightings on each neuron are adjusted
Once the errors in the output have been eliminated (or reduced to acceptable
limits) the neural network is functioning correctly and the model has been
successfully set up
If the errors are still too large, the weightings are altered - the process continues
until satisfactory outputs are produced
2 Types:
1. Static
Computer Science 65
Static maps static inputs to a static output
Mapping is instantaneous
2. Recurrent
Regression
Searches for a specified value in a list/array by comparing every single element until
the value has been found
import numpy as np
Pew = np.array([1,6,8,4,9])
print (Pew)
x=1
def linearsearch(Pew,x):
for i in range(len(Pew)):
if Pew[i] == x:
return i
return -1
result = linearsearch(Pew,x)
if (result == -1):
print("Wrong one")
else:
print ("i am here")
Searches for a specified value in a list/array by comparing the specified value with the
current middle value, where the list is split in half and the unwanted portion is rejected
each time to narrow down the search
Computer Science 66
import numpy as np
Pew = np.array([7,12,19,23,27,33,37,41,45,56,59,60,62,71,75,80,84,88,92,99])
print (Pew)
x = int(input("What number are you trying to find?"))
1. Find the middle value and compare the required value with this middle value
2. if not found then discard either the top half or bottom half of the list
How the performance of a binary search varies according to the number of data items
Very efficient for finding a particular value, since the size of the list is halved for every
iteration
Sorting Algorithm
import numpy as np
Pew = np.array([53,21,60,18,42,19])
print (Pew)
def insertionsort(Pew):
for pointer in range(len(Pew)):
x = Pew[pointer]
p = pointer -1
Computer Science 67
insertionsort(Pew)
print (Pew)
import numpy as np
Pew = np.array([8,3,4,6,5,7,2])
print (Pew)
def bubblesort(Pew):
length = len(Pew)-1
unsorted = True
while unsorted:
unsorted = False
for i in range (0, length):
#change > to < for descending order
if Pew[i] > Pew[i+1]:
hold = Pew[i+1]
Pew[i+1] = Pew[i]
Pew[i] = hold
print (Pew)
unsorted = True
bubblesort(Pew)
Performance of a sorting routine may depend on the initial order of the data and the
number of data items
Show understanding that a graph is an example of an ADT. Describe the key features of a
graph and justify its use for a given situation
Stack
EMPTYSTRING = ""
NullPointer = -1
MaxStackSize = 8
global BaseOfStackPointer
global TopOfStackPointer
global Stack
Stack = [EMPTYSTRING] * MaxStackSize
def InitialiseStack():
global BaseOfStackPointer
global TopOfStackPointer
BaseOfStackPointer = 0
Computer Science 68
TopOfStackPointer = NullPointer
#INSERT
def Push(NewItem):
global BaseOfStackPointer
global TopOfStackPointer
global Stack
if TopOfStackPointer < MaxStackSize - 1:
TopOfStackPointer = TopOfStackPointer + 1
Stack[TopOfStackPointer] = NewItem
#DELETE
def Pop():
global BaseOfStackPointer
global TopOfStackPointer
global Stack
Item = EMPTYSTRING
if TopOfStackPointer > NullPointer:
Stack[TopOfStackPointer] = Item
TopOfStackPointer = TopOfStackPointer - 1
return Item
def menu():
print("Welcome to - THE STACK")
print("1. Initialise Stack")
print("2. Push new item")
print("3. Pop an item")
query = input("Select the number of desired operation")
if query == "1":
InitialiseStack()
elif query == "2":
NewItem = input("Enter the item you would like to push to the stack")
Push(NewItem)
elif query == "3":
Pop()
print("This is what the Stack looks like now:")
print(Stack)
menu()
# print("Would you like to do something else?")
# retry = input("[Y/N]")
# if retry == "Y" or retry == "y":
# menu()
menu()
Queue
# Initializing a queue
queue = []
print("Initial queue")
Computer Science 69
print(queue)
# Uncommenting print(queue.pop(0)) will raise and IndexError as the queue is now empty
Linked List
#initializing
class node:
def __init__(self, data=None):
self.data=data
self.next=None
class linked_list:
def __init__(self):
self.head = node()
def append(self,data):
new_node = node(data)
cur = self.head
while cur.next!=None:
cur = cur.next
cur.next = new_node
def length(self):
cur = self.head
total = 0
while cur.next!= None:
total += 1
cur = cur.next
return total
Computer Science 70
while True:
cur_node=cur_node.next
if cur_idx==index: return cur_node.data
cur_idx+=1
#ERASE
def erase(self,index):
if index>=self.length():
print ("ERROR: 'Erase' index out of range")
return
cur_idx=0
cur_node=self.head
while True:
last_node = cur_node
cur_node = cur_node.next
if cur_idx==index:
last_node.next = cur_node.next
return
cur_idx+=1
my_list = linked_list()
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)
my_list.erase(1)
print(my_list.get(2))
my_list.display()
Dictionary
Creating a dictionary
d = {}
l = []
d[1] = "yes"
d['1'] = "No"
d[2]=9000
class my_class:
def __init__(self):
self.data = "data"
instance = my_class()
d['object'] = instance
d['object'].data
print(d['object'].data)
print(d.keys())
print(d.items())
print (d)
Computer Science 71
Accessing Elements from Dictionary
class_names = ["jack","bob","sarah","asahi","mikael","gloria","alan","bruno","sekita"]
def create_dataset():
import random
num_entries = 1000
f = open("data.txt","w")
for i in range(num_entries):
current = random.choice(class_names)
f.write(current+"\n")
f.close()
def read_dataset_list():
class_counts = []
for c in class_names:
class_counts.append(0)
with open("data.txt","r") as f:
for line in f:
line = line.strip()
if line!="":
class_counts[class_names.index(line)]+=1
print (class_counts)
def read_dataset_dict():
class_counts = {}
for c in class_names:
class_counts[c] = 0
with open("data.txt") as f:
for line in f:
line = line.strip()
if line!=" ":
class_counts[line]+=1
print (class_counts)
import time
t0 = time.time()
create_dataset()
t1 = time.time()
print (t1-t0)
t0 = time.time()
read_dataset_list()
t1 = time.time()
print (t1-t0)
t0 = time.time()
read_dataset_dict()
t1 = time.time()
print (t1-t0)
Computer Science 72
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# Throws Error
print(squares)
Binary Tree
Computer Science 73
print('Inorder of nodes :', root.inorder)
print('Size of tree :', root.size)
print('Height of tree :', root.height)
print('Properties of tree : \n', root.properties)
class node:
def __init__(self,value=None):
self.value=value
self.left_child=None
self.right_child=None
self.parent=None # pointer to parent node in tree
class binary_search_tree:
def __init__(self):
self.root=None
def insert(self,value):
if self.root==None:
self.root=node(value)
else:
self._insert(value,self.root)
def _insert(self,value,cur_node):
if value<cur_node.value:
if cur_node.left_child==None:
cur_node.left_child=node(value)
cur_node.left_child.parent=cur_node # set parent
else:
self._insert(value,cur_node.left_child)
elif value>cur_node.value:
if cur_node.right_child==None:
cur_node.right_child=node(value)
cur_node.right_child.parent=cur_node # set parent
else:
self._insert(value,cur_node.right_child)
else:
print("Value already in tree!")
def print_tree(self):
if self.root!=None:
self._print_tree(self.root)
def _print_tree(self,cur_node):
if cur_node!=None:
self._print_tree(cur_node.left_child)
print (str(cur_node.value))
self._print_tree(cur_node.right_child)
def height(self):
if self.root!=None:
return self._height(self.root,0)
else:
return 0
def _height(self,cur_node,cur_height):
if cur_node==None: return cur_height
left_height=self._height(cur_node.left_child,cur_height+1)
right_height=self._height(cur_node.right_child,cur_height+1)
Computer Science 74
return max(left_height,right_height)
def find(self,value):
if self.root!=None:
return self._find(value,self.root)
else:
return None
def _find(self,value,cur_node):
if value==cur_node.value:
return cur_node
elif value<cur_node.value and cur_node.left_child!=None:
return self._find(value,cur_node.left_child)
elif value>cur_node.value and cur_node.right_child!=None:
return self._find(value,cur_node.right_child)
def delete_value(self,value):
return self.delete_node(self.find(value))
def delete_node(self,node):
# returns the node with min value in tree rooted at input node
def min_value_node(n):
current=n
while current.left_child!=None:
current=current.left_child
return current
Computer Science 75
node_parent.right_child=child
else:
self.root=child
child.parent=node_parent
if node_children==2:
successor=min_value_node(node.right_child)
node.value=successor.value
self.delete_node(successor)
#SEARCH
def search(self,value):
if self.root!=None:
return self._search(value,self.root)
else:
return False
def _search(self,value,cur_node):
if value==cur_node.value:
return True
elif value<cur_node.value and cur_node.left_child!=None:
return self._search(value,cur_node.left_child)
elif value>cur_node.value and cur_node.right_child!=None:
return self._search(value,cur_node.right_child)
return False
#INSERTING
tree=binary_search_tree()
tree.insert(1)
tree.insert(2)
tree.insert(3)
tree.insert(4)
tree.print_tree()
print (tree.search(1))
Describe the following ADTs and demonstrate how they can be implemented from
appropriate built-in types or other ADTs: stack, queue, linked list, dictionary, binary tree
Show understanding that different algorithms which perform the same task can be compared
by using criteria (e.g. time taken to complete the task and memory used)
Bubble Sort required temporary memory for only a single data item
Bubble Sort recognises that the list is completely sorted and will stop
Recursion
Computer Science 76
Show understanding of recursion
Understanding of and ability to write low level code that uses various addressing modes:
immediate, direct, indirect, indexed, and relative
Understanding of and ability to write imperative (procedural) programming code that uses
variables, constructs, procedures, and functions
Understanding of and ability to write code that demonstrate the use of OOP
Understanding of and ability to solve a problem by writing appropriate facts and rules
based on supplied information
Understanding of and ability to solve a problem by writing appropriate facts and rules
based on supplied information
Computer Science 77
Write code to perform file-processing operations
Computer Science 78