0% found this document useful (0 votes)
42 views51 pages

Computer Science Paper 1 #RS421 (By Ryan Sutton)

The document outlines topics related to programming fundamentals including data types, operations, control structures, algorithms and more. It discusses concepts such as variables, constants, arithmetic, relational and boolean operations. Sections cover programming paradigms, data structures including queues, stacks, graphs and trees as well as algorithms for graph and tree traversal.

Uploaded by

K B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views51 pages

Computer Science Paper 1 #RS421 (By Ryan Sutton)

The document outlines topics related to programming fundamentals including data types, operations, control structures, algorithms and more. It discusses concepts such as variables, constants, arithmetic, relational and boolean operations. Sections cover programming paradigms, data structures including queues, stacks, graphs and trees as well as algorithms for graph and tree traversal.

Uploaded by

K B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Ryan Sutton Paper 1 - EBook

Spec: Here; Key terms: Here; Checklist (PERLLs): Here

4.1 Fundamentals of Programming -


4.1.1 Programming -
4.1.1.1 Data types (AS) -
4.1.1.2 Programming Concepts (AS) -
4.1.1.3 Arithmetic operations in a programming language (AS) -
4.1.1.4 Relational operations in a programming language (AS) -
4.1.1.5 Boolean operations in a programming language (AS) -
4.1.1.6 Constants and variables in a programming language (AS) -
4.1.1.7 String-handling operations in a programming language (AS) -
4.1.1.8 Random number generation in a programming language (AS) -
4.1.1.9 Exception handling (AS) -
4.1.1.10 Subroutines (procedures/functions) -
4.1.1.11 Parameters of subroutines -
4.1.1.12 Returning a value/values from a subroutine
4.1.1.13 Local variables in subroutines -
4.1.1.14 Global variables in a programming language
4.1.1.15 Role of stack frames in subroutine calls
4.1.1.16 Recursive techniques
4.1.2 Programming paradigms
4.1.2.1 Programming paradigms
4.1.2.2 Procedural-oriented programming (AS)
4.1.2.3 Object-oriented programming
4.2 Fundamentals of Data Structures -
4.2.1 Data Structures and abstract data types -
4.2.1.1 Data Structures -
4.2.1.2 Single- and multi-dimensional arrays (or equivalent)
4.2.1.3 Fields, records and files
4.2.1.4 Abstract data types/data structures
4.2.2 Queues
4.2.2.1 Queues
4.2.3 Stacks
4.2.3.1 Stacks
4.2.4 Graphs
4.2.4.1 Graphs
4.2.5 Trees
4.2.5.1 Trees (including binary trees)
4.2.6 Hash tables
4.2.6.1 Hash tables
4.2.7 Dictionaries
4.2.7.1 Dictionaries
4.2.8 Vectors
4.2.8.1 Vectors
4.3 Fundamentals of algorithms
4.3.1 Graph-traversal
4.3.1.1 Simple graph-traversal algorithms
4.3.2 Tree-traversal
4.3.2.1 Simple tree-traversal algorithms
4.3 Fundamentals of algorithms
4.3.3 Reverse Polish
4.3.3.1 Reverse Polish – infix transformations
4.4 Theory of Computation
4.4.1 Abstraction and automation -
4.4.1.1 Problem-solving (AS)
4.4.1.2 Following and writing algorithms (AS)
4.4.1.3 Abstraction (AS)
4.4.1.4 Information hiding (AS)
4.4.1.5 Procedural abstraction (AS)
4.4.1.6 Functional abstraction (AS)
4.4.1.7 Data abstraction (AS)
4.4.1.8 Problem abstraction/reduction (AS)
4.4.1.9 Decomposition (AS)
4.4.1.10 Composition (AS)
4.4.1.11 Automation (AS)
Abstraction Worksheet 1 -
4.4.2 Regular Languages
4.4.2.1 Finite state machines (FSMs) {with and} without output {AS}
4.4.2.2 Maths for regular expressions
4.4.2.3 Regular expressions
4.4.2.4 Regular language
4.4.3 Context-free languages
4.4.3.1 Backus-Naur Form (BNF)/syntax diagrams
4.4.4 Classification of algorithms
4.4.4.1 Comparing algorithms
4.4.4.2 Maths for understanding Big-0 notation
4.4.4.3 Order of complexity
4.4.4.4 Limits of computation
4.4.4.5 Classification of algorithmic problems
4.4.4.6 Computable and non-computable problems
4.4.4.7 Halting problem
4.4.5 A model of computation
3.4.1.5 Procedural Abstraction -
3.4.1.6 Functional Abstraction -
3.4.1.6 Data Abstraction -
4.1 Fundamentals of Programming -
Prove it workbook.

4.1.1 Programming -
4.1.1.1 Data types (AS) -
● Understand the concept of a data type. ✓
Data type
Determines what sort of data is being stored and how it will be handled by the program.

● Understand and use the following appropriately:


○ Integer✓
Integer
A whole rational number
○ Real/float✓
Real / float
A real number with a decimal point/ fractional part
○ Boolean✓
Boolean
A True or False statement
○ Character✓
Character
A singular ‘item’- one letter, special character or number.
○ String✓
String
A collection of characters normally defined by speech or quotation marks in coding. This
can be a singular word or a phrase.
○ Date/time✓
Date / Time
Numbered dates or times.
○ Pointer/reference
Pointers or references
○ Records (or equivalent)✓
Record
A basic data structure, can contain a variety of data types within it. Typically in fixed
number and sequence - usually about a singular topic or a variety of topics within a same
area.
○ Arrays (or equivalent).✓
Array / List
A collection of elements; usually defined by square brackets. The elements can be strings,
integers, floats or etc.

● Variables declared as a pointer or reference data type are used as stores for memory addresses
of objects created at runtime, ie dynamically. Not all languages support explicit pointer types, but
students should have an opportunity to understand this data type.

● Define and use user-defined data types based on language-defined (built-in) data types.
User defined data type
A customizable data type which is used to extend current data types or create new ones.
4.1.1.2 Programming Concepts (AS) -
● Use, understand and know how the following statement types can be combined in programs:
○ Variable declaration assignment
Variable Declaration - A data item whose value will change during the execution of the
program. A variable declaration is setting such variable, declaring its name and contents -
changing (or creating) a state for it.

○ Constant declaration
Constant Declaration - An item of data whose value does not change with the program. The
declaration of such variable is initial, and final.

○ Assignment
Assignment - The process of giving a value to a variable or constant.

○ Iteration
Iteration - ‘For’ or ‘While’ Loops. Repeating the same process several times in order to
achieve a result.

○ Selection
Selection - ‘If Statement’ - The principle of choosing what action to take based on certain
criteria.

○ Subroutine (procedure/function).
Subroutine (Procedure/function) - Function is fun, returns a value. Procedures don’t return
values. A named block of code designed to carry out a specific task.

○ The three combining principles (sequence, iteration/repetition and selection/choice) are


basic to all imperative programming languages.

● Use definite and indefinite iteration, including indefinite iteration with the condition(s) at the start
or the end of the iterative structure. A theoretical understanding of condition(s) at either end of an
iterative structure is required, regardless of whether they are supported by the language being
used.

● Use nested selection and nested iteration structures.

● Use meaningful identifier names and know why it is important to use them
Meaningful identifier names = Understandable names that name what they store. E.g ‘Number’
for an integer.

Importance -
● Variables easily traced through scopes
● Code is easily understood - Variables names detail what could be stored and potentially
its use.

4.1.1.3 Arithmetic operations in a programming language (AS) -

All in python 3.
● Be familiar with and be able to use:
○ Addition
Num.1 + Num.2

○ Subtraction
Num.2 - Num.1

○ Multiplication
Num.1 * Num.2

○ Real/float division
Num.2 / Num.1

○ Integer division, including remainders


Integer Div w/o remainders (Num.2 // Num.1); Modulo Div (Num.2 % Num.1).

○ Exponentiation
Num.1 ** Num.2

○ Rounding
round(Num.1)

Import math
math.floor (3.5) #Output 3.0
math.floor (-3.5) #Output -4.0
math.ceil(3.5) # Output 4.0
math.ceil(-3.5) # Output -3.0

○ Truncation.
import math
math.trunc(3.5) # Output of 3

4.1.1.4 Relational operations in a programming language (AS) -


● Be familiar with and be able to use:
○ Equal to
‘==’ in python
○ Not equal to
!=' in python
○ Less than
Number 1 is less than number 2
Num.1 < Num.2
○ Greater than
Number 2 is greater than number 1
Num.2 > Num.1
○ Less than or equal to
Number 1 is less than or equal to Number 2
Num.1 <= Num.2
○ Greater than or equal to.
Number 2 is greater or equal to Number 1.
Num.2 >= Num.1

4.1.1.5 Boolean operations in a programming language (AS) -


● Be familiar with and be able to use:
○ NOT
‘not’ in python
○ AND
‘and’ in python
Boolean operator : &
○ OR
‘or’ in python
Boolean operator : |
○ XOR.
^ in python

4.1.1.6 Constants and variables in a programming language (AS) -


● Be able to explain the differences between a variable and a constant.
Variable = value is changed
Constant = value is never changed after initialisation

● Be able to explain the advantages of using named constants.


If the constant is used multiple times it may be better to give it a name rather than copying the
whole number or value - if large; over and over again.
A compiler may be able to tell the developer that they have changed a constant within their code.

4.1.1.7 String-handling operations in a programming language (AS) -


Documentation
● Be familiar with and be able to use:
○ Length
len() in python
○ Position
string_name[No_of_position]
list_name[No_of_position]
Etc...
○ Substring
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
○ Concatenation
- In formal language theory and computer programming, string concatenation is the
operation of joining character strings end-to-end. For example, the concatenation
of "snow" and "ball" is "snowball".
>>>A = “snow”
>>>B = “ball’
>>>print(A,B)
‘snow ball’
>>>print(A+B)
‘snowball’

○ Character → character code


>>> s = 'hi'
>>> [ord(c) for c in s]
[104, 105]

○ Character code → character


c = [chr(x) for x in [104,105]]
print (c)
[‘h’,’i’]

○ String conversion operations.


■ Expected string conversion operations:
● String to integer
int(string_name)
● String to float
float(string_name)
● Integer to string
str(integer_name)
● Float to string
str(float_name)
● Date/time to string
str(date_time_name)
● String to date/time.
>>> from datetime import datetime
>>> datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y
%I:%M%p')

4.1.1.8 Random number generation in a programming language (AS) -


● Be familiar with, and be able to use, random number generation.
>>> import random
>>>print(random.randint(0,1))
#Outputs either 0 or 1

4.1.1.9 Exception handling -


● Be familiar with the concept of exception handling.
Logic Error -
When the expected output doesn’t meet the actual output, but the code doesn’t crash.
Normally when math goes wrong within a program (a developer’s hard coded error).
Syntax Error -
An error with grammar or with the formatting of the functions or otherwise within the code.

Runtime Error -
Occurs when the program is running.

● Know how to use exception handling in a programming language with which students are
familiar.
Exception Handling -
Part of a robust program. In order to disallow crashing of programs through unexpected inputs,
this is used.

If no other way of testing exception handling can be used; the ultimate method is...
In python:
Try
Except

Exception handling can allow for error messages, to inform and possibly, to avoid fatal crashes.

Questions found here:


https://docs.google.com/document/d/1ZS29caLN2Xz4JbKZGl0bCCtp2mUG6n8yRzZvxZrhScg/e
dit

(a) Look at the main program. Explain what the following statement does:
IF option = "1"
saveToFile("write")
If the user inputs 1 as their option. The program will run the saveToFile subroutine with “write” as
it’s openMode parameter being passed in. IWhen running the subroutine, it will open the
studentNamesfile.txt in write mode, the user will be asked for a name of a student and then to
enter their mark, saving this name and mark as a record within the file opened previously. There is
a while loop to iterate this process until the user enters “xxx”. The user also has the option to enter
“xxx” as the original input and go back to the main menu.

(b) In the subroutine saveToFile, what mode is the file opened in? Where is the file saved?

#subroutine to input data and save to a new file


SUB saveToFile(openMode)
#open testResultFile in correct mode
testResultsFile = OPEN("studentNamesfile.txt",openMode)

As said before, the file is opened in write mode and the file is saved as “studentNamesfile.txt”

4.1.1.10 Subroutines (procedures/functions) -


● Be familiar with subroutines and their uses.
Functions are fun because they return values. Procedures do not.
Functions are subroutines that may take in one or more parameters whilst returning a value.
Parameters appear in subroutine definitions and arguments appear in subroutine calls.

● Know that a subroutine is a named ‘out of line’ block of code that may be executed (called) by
simply writing its name in a program statement.

● Be able to explain the advantages of using subroutines in programs.


Advantages -
Breaking down problems into smaller sections - which individually can be run and error checked
(as well as debugged).
Prevents the need to rewrite parts of code again when a certain function or action is needed
twice in the same program.

4.1.1.11 Parameters of subroutines -


● Be able to describe the use of parameters to pass data within programs.
Parameters allow for inputs into subroutines in order to get a customised output or returned
value/ action to use on the program.

● Be able to use subroutines with interfaces.


Creating a subroutine that in itself calls all of the different subroutines, that does no calculations.
Containing what could be in the main program to its own

4.1.1.12 Returning a value/values from a subroutine


● Be able to use subroutines that return values to the calling routine.
def main(changed_variable)
variable_name = changed_variable
return variable_name

4.1.1.13 Local variables in subroutines -


● Know that subroutines may declare their own variables, called local variables, and that local
variables: • exist only while the subroutine is executing • are accessible only within the subroutine.
Local Variable -
Declared and used inside a subroutine, only available to that routine. Created when the routine is
called and discarded when ended.

● Be able to use local variables and explain why it is good practice to do so.
For these reasons:
● It reduces the complexity of the code - allowing variables to be more easily traced as there
is only one iteration of it within the code - rather than many iterations used in many places.
● It adds ‘complexity’ over the whole program; instead of over one subroutine.
● It stops the big problem where changing one subroutine causes damage to another.

4.1.1.14 Global variables in a programming language


● Be able to contrast local variables with global variables.
Scopes -
The scope of a local variable is within a subroutine, and the scope of a global variable is the whole
program.
Global Variable -
Declared at the top of a program outside of subroutines. Usable throughout the program, created
when program starts, discarded when it end.

4.1.1.15 Role of stack frames in subroutine calls

● Be able to explain how a stack frame is used with subroutine calls to store:
○ Return addresses
○ Parameters
○ Local variables.
Stacks can Push, Pop, Peek or top, Test for empty stack, Test for stack full.
Parameters and return addresses. 2/2

A single stack can be used through the usage of stack frames. The first action (1) is stored in a
stack with it’s parameters, return address, it will then run the subroutine and do it’s function,
storing local variables on the way. When another subroutine is called, it will push (1) this onto the
stack and run it’s respective code, storing all the same variables in the stack frame.
For instance, if the user chooses to run repeat, repeat, undo, repeat. The stack frame will push 1
stack of repeat, run it’s code and store variables, then run another repeat, then when undo is
called, the code will run for its respective subroutine and push it onto the stack, however what can
be done is that the undo function can traverse the stack frame or peek at it and refer back to 2
subroutines ago (the first repeat call) and alter the state of the software in order to go back to that
first stack, or it can pull the top subroutine call in the stack essentially undoing anything that the
second repeat call did. The software then runs another repeat call, pushing it onto the stack on
top of the first, leaving the code with two repeat calls altogether in the stack frame. The code will
then run the two repeat calls accordingly and pull them off the stack when they’re operation is
done. x

1) Stack / data structure is used to store the (user’s) actions; A. by implication


2) Each time an action is completed it is pushed/added onto the top of the stack;
3) unless it is an undo (or repeat) action;
4) When repeat action is used the top item from the stack is used to indicate the action to complete
// when repeat action is used the result of peek function is used to indicate the action to complete;
R. implication that top item of stack is popped/deleted from stack – unless it is clear it is
subsequently pushed/added back to the stack A. when repeat action is used a copy of the top
item from the stack is pushed/added to the top of the stack.
5) When undo action is used the top item is popped/removed from the stack of actions;

Runtime Error. 0/1


Correct : stack empty

4.1.1.16 Recursive techniques


● Be familiar with the use of recursive techniques in programming languages (general and base
cases and the mechanism for implementation).
● Be able to solve simple problems using recursion.

Questions here: https://drive.google.com/file/d/1OmYeU8QF76quf_W85_EiRAGZY63OAA88/view

1)
a) Hierarchical structure ~
No Loops v

b) A loop, e.g a corridor that leads back to the start of the maze (e.g one of the 6 corridors
leading back to 1). v

c)
4.1.2 Programming paradigms
4.1.2.1 Programming paradigms
● Understand the characteristics of the procedural- and object-oriented programming paradigms,
and have experience of programming in each.

4.1.2.2 Procedural-oriented programming (AS)


● Understand the structured approach to program design and construction.
○ High usage of procedures and functions to repeat assignment, selection and iteration.
○ Decomposition of bigger tasks.
○ Global and local variables.

● Be able to construct and use hierarchy charts when designing programs.

● Be able to explain the advantages of the structured approach.


Advantages:
○ Simplicity
○ Modularity
○ Repeatability
○ Makes maintaining programs easier (bugs are confined).
○ Easier to test.
○ Can split development into a team.

4.1.2.3 Object-oriented programming


Presentation
Presentation 2
Video
Worksheet, (H/W) Worksheet 2
OOPprogrammingChallengeWorksheet
Procedural -
● step-by-step instructions
● calls to subroutines (procedures or functions)
● local and global variables
Object-oriented Programming -
● Models real world issues.
● Objects which have code individually.
● Persons, animals, events, data structures - all separate.

● Be familiar with the concepts of:


○ Class.
A Blueprint which can be multiplied.
Defines the properties and methods of a group of similar objects (defines the related
group of things).
Contains properties which describe:
■ What the data are and the methods
■ The way in which the data can behave.
■ Classes can be created based on other classes
○ Object.
A specific instance of an class
It will have the same properties and methods from the class from which it is built.
It will also contain the data on which the methods will be run.
○ Instantiation.
The process of creating an object from a class.
In programming a subroutine called a constructor will be called.
○ Encapsulation.
Keeping everything within 1 place to arrange it neatly and contain all bugs.
○ Inheritance.
Methods and Attributes inherited by objects/ subclass, from super classes.
○ Aggregation.
Specific form of n
■ A class is a collection/ container of other classes
■ The contained classes do not have a strong dependency on the container class
■ If the container class is destroyed the associated classes still exist.
○ Composition.
An object is created in a ‘subclass’ instead of inheriting. Advantage: apple not to conform
to the interface of their previous parent. Could be a good thing, sometimes change to the
superclass has effects on the subclasses; still has access to the properties and
behaviours of these classes through private instances, and if they want to expose these
former-superclass behaviours, they can simply wrap them in a public method.

Inheritance = ‘is a’
Plane ‘is a’ form of transport

Association = ‘has a’
Student ‘has a’ Teacher
Player ‘has a’ Coach

Independent in association.

Stronger form of Association :


■ Class is a collection/ container of other classes.
■ The contained classes do have a strong dependency on the container class.
■ If the container class is destroyed the associate classes are also destroyed.

○ Polymorphism
The change of a property that has been inherited within a subclass.

○ Overriding.
(The action of polymorphism)
Dynamic polymorphism, subclass provides a specific implementation of a method that is
already provided by a parent class

○ Students should know that:


■ A class defines methods and property/attribute fields that capture the common
behaviours and characteristics of objects
■ Objects based on a class are created using a constructor, implicit or explicit, and a
reference to the object assigned to a reference variable of the class type
■ In the Unified Modelling Language (UML) composition is represented by a black
diamond line and aggregation by a white diamond line.

Similar to a flow chart; shows how classes and objects act.

Object:
Student

Attributes:
- Name
- Age
- Gender
- Height
- Nationality
- Weight

Methods:
- Raise()
- Walk()
- Sit()
- Toilet()
- Sing()
- Eat()

● Know why the object-oriented paradigm is used.


Advantages -
○ Provides a clear modular format
○ Produces reusable code; inheritance/encapsulation.
○ More efficient to use with pre-defined/ inherited objects/ classes
○ Code contains fewer errors because of self contained object.

● Be aware of the following object-oriented design principles:


○ Encapsulate what varies.
○ Favour composition over inheritance.
○ Program to interfaces, not implementation.
■ Students would benefit from practical experience of programming to an interface,
but will not be explicitly tested on programming to interfaces or be required to
program to interfaces in any practical exam.

● Be able to write object-oriented programs.


○ Practical experience of coding for user-defined classes involving:
■ Abstract, virtual and static methods.
■ Inheritance.
■ Aggregation.

■ Polymorphism.

■ Public, private and protected specifiers.


● Public Specifier
○ Accessed anywhere in the program. This isn’t good practice.
○ No underscores
● Protected Specifier
○ Accessed exclusively the class and it’s children.
○ 1 underscore before variable name
● Private Specifier
○ Accessed only by the class and it’s objects.
○ 2 underscores and mangled class name when referencing

● Be able to draw and interpret class diagrams.


○ Class diagrams involving single inheritance, composition (black diamond line),
aggregation (white diamond line), public (+), private (-) and protected (#) specifiers.
4.2 Fundamentals of Data Structures -
G-Site

4.2.1 Data Structures and abstract data types -


4.2.1.1 Data Structures -
Presentation
● Be familiar with the concept of data structures.
○ It may be helpful to set the concept of a data structure in various contexts that students
may already be familiar with. It may also be helpful to suggest/demonstrate how data
structures could be used in a practical setting.

Data Structures - A common format for storing large volumes of related data, which is an
implementation of an abstract data type.

Mindmap

4.2.1.2 Single- and multi-dimensional arrays (or equivalent)


● Use arrays (or equivalent) in the design of solutions to simple problems.
○ A one-dimensional array is a useful way of representing a vector. A two-dimensional array
is a useful way of representing a matrix. More generally, an n-dimensional array is a set of
elements with the same data type that are indexed by a tuple of n integers, where a tuple
is an ordered list of elements

Difference between an array and a list -


An array is always a fixed length, while a list is not.
4.2.1.3 Fields, records and files
● Be able to read/write from/to a text file.
with open( path, ‘r’, ‘utf-8’) as myfile:
myfile.read()

Field - An item of data.


Record - One line of a text file.

● Be able to read/write data from/to a binary (nontext) file.


Iid = formatting for string files.

4.2.1.4 Abstract data types/data structures


● Be familiar with the concept and uses of a:
○ Queue
○ Stack
○ Graph
○ Tree
○ Hash table
○ Dictionary
○ Vector.
■ Be able to use these abstract data types and their equivalent data structures in
simple contexts. Students should also be familiar with methods for representing
them when a programming language does not support these structures as built-in
types.

Data Structure - A common format for storing large volumes of related data, which is an
implementation of an abstract data type.

Abstract data type - A conceptual model of how data can be stored and the operations that can
be carried out on the data.

● Be able to distinguish between static and dynamic structures and compare their uses, as well as
explaining the advantages and disadvantages of each.
Static - Size doesn’t change.

Dynamic - Size can change.

● Describe the creation and maintenance of data within:


○ Queues (linear, circular, priority)
○ Stacks
○ Hash tables.

4.2.2 Queues
4.2.2.1 Queues
G-Site
Presentation
● Be able to describe and apply the following to linear queues, circular queues and priority queues:
○ Add an item
○ Remove an item
○ Test for an empty queue
○ Test for a full queue.

Queue - An abstract data structure that follows a first in first out (FIFO) order. Data leaves in the
order it arrives.

A queue may be used when a peripheral wants to send data to a CPU. However, it may not be
ready for such information and therefore may temporarily store the data in a queue.

Actions:
● enQueue(item)
○ Always check to see if queue is full → return error.
● deQueue
○ Always check to see if queue is empty → return error.
● isEmpty
● isFull

Linear Queue

- A FIFO structure organised as a line of data such as a list.

● Two pointers: one at the front and one at the end (pointing to the index of the last stored item).
● Has a maximum size.
● Typically implemented as a 1D array.

All actions work as they normally would

Circular Queue
- A FIFO data structure implemented as a ring where the front and rear pointers can wrap
around from the end to the start of the array.

● Implemented as a fixed size ring.


● Back of queue is connected to the front.
● Pointers move and data stays until overwritten.

Commonly used when buffering, when items of data need to be stored temporarily while they are
waiting to be passed to/from a device.

A circular queue is full when the tail pointer is 1 less than the front pointer.

Priority Queue

- A variation of a FIFO structure where some data may leave out of sequence where it has a
higher priority than other items.

● Adds a further element to the queue which is the priority for each item.

For example if documents are being sent to print on a network printer then it might be possible for
the user or systems manager to control the queue in some way.

Depending on how the priority queue is implemented, the enqueue and dequeue may pick an
element in the middle of the array due to priority.

4.2.3 Stacks
4.2.3.1 Stacks
G-Site
Presentation
● Be able to describe and apply the following operations:
○ Push
○ Pop
○ Peek or top
○ Test for empty stack
○ Test for stack full.
■ Peek or top returns the value of the top element without removing it.
Stack - A LIFO (Last in, First out) structure where the last item of data added is the first to leave.
One pointer on the top of the stack

Stacks can overflow (full + adding 1 more) and underflow (empty + taking away 1).

Used in stack frames.

Actions:
● push(item) – adds item to the top of the stack.
○ Always check to see if stack is full → report an error.
● pop() – removes and returns the item on the top of the stack.
○ Always check to see if stack is empty → report an error.
● isFull() – checks if the stack is full.
● isEmpty() – checks if the stack is empty.
● peek() – return the top item without removing it.
● size() – return the number of items on the stack.

Stack Frames

Stack Frame - A collection of data about a subroutine call - a system level data structure.

Calls to subroutines are executed as follows:


1. The parameters are saved onto the stack
2. Local variables are saved onto the stack
3. The address to which execution returns after the end of the subroutine is reached is saved
onto the stack
4. Execution is transferred to the subroutine code

Subroutines are executed as follows:


1. Stack space is allocated for local variables
2. The subroutine code executes
3. The return address is retrieved
4. The parameters are popped
5. Execution is transferred back to the return address

4.2.4 Graphs
4.2.4.1 Graphs
G-Site
Presentation
● Be aware of a graph as a data structure used to represent more complex relationships.
● Be familiar with typical uses for graphs.
● Be able to explain the terms:
○ Graph
○ Weighted graph
○ Vertex/node
○ Edge/arc
○ Undirected graph
○ Directed graph.
● Know how an adjacency matrix and an adjacency list may be used to represent a graph.
● Be able to compare the use of adjacency matrices and adjacency lists.

Graph - A mathematical structure that models the relationship between pairs of objects.
Weighted Graph - A graph that has a data value labelled on each edge.
Vertex/node - An object in a graph.
Edge/Arc - A join or relationship between two nodes.
Undirected graph - A graph where the relationship between vertices is two-way
Directed graph - A graph where the relationship between vertices is one way.

Uses of graphs:
● Modelling:
○ Human networks (social, family, work). E.g LinkedIn.
○ Transport Networks.
○ Internet and web.
○ Computer science: Latency is a big factor so a graph could be used to calculate
the quickest path to send data around a microprocessor.
○ Medical Research: Diseases.
○ Project management.
○ Game theory.
○ Djikstra’s algorithm.

Graph (Undirected)

Weighted Graph
Directed Graph

Adjacency matrix
0’s where the blanks are.

● Advantage: an adjacency matrix is convenient to work with, and adding an edge is simple
● Disadvantage: a sparse graph with not many connections (edges) will leave most of the cells
empty, wasting a lot of memory space

Adjacency list
● It only uses storage for the connections that exist, so it is more (memory) space-efficient.
● It is a good way of representing a large, sparsely connected graph.

4.2.5 Trees
4.2.5.1 Trees (including binary trees)
G-Site
Presentation
● Know that a tree is a connected, undirected graph with no cycles.
○ Note that a tree does not have to have a root.
● Know that a rooted tree is a tree in which one vertex has been designated as the root. A rooted
tree has parent-child relationships between nodes. The root is the only node with no parent and
all other nodes are descendants of the root.
● Know that a binary tree is a rooted tree in which each node has at most two children.
○ A common application of a binary tree is a binary search tree.
● Be familiar with typical uses for rooted trees.

Tree - A data structure similar to a graph, with no loops (hierarchical). A tree does not have to have
a root.

Node/Vertex - An object in a graph.


Edge/Arc - A join of relationship between nodes.

Root - The starting node in a rooted tree structure from which all other nodes branch off.
Parent - A type of node in a tree where there are further nodes below it.
Child - A node in a tree that has nodes above it in the hierarchy.
Leaf - A node that does not have any other nodes beneath it.

Uses:
● Store data that has an inherent hierarchical structure. OS may use trees for directories,
files and folders in it's file management system.
● Process the syntax of statements in natural and programming languages, so they are
commonly used when compiling programming code.
Advantages:
● Dynamic, easy to delete and add nodes.
● Easy to search with standard traversal algorithms.

Disadvantages:
● Trees need to be balanced (height of the tree is kept to a minimum( to conserve space.

Rooted Tree

Binary Tree

2 children for each parent node.

Building a (binary) tree:


● Starting at the root each time, if the next item is less than the root, it is added to the left of the root,
otherwise, to the right.
● Apply the same rule at the root of each sub-tree.
Traversing a tree

4.2.6 Hash tables


4.2.6.1 Hash tables
G-Site
Presentation
● Be familiar with the concept of a hash table and its uses.
○ A hash table is a data structure that creates a mapping between keys and values.
● Be able to apply simple hashing algorithms.
● Know what is meant by a collision and how collisions are handled using rehashing.
○ A collision occurs when two key values compute the same hash.
Hash table - A data structure that stores key/value pairs based on an index calculated from an
algorithm.
Key/Value pair - The key and it's associated data.

Hashing algorithm - Code that creates a unique index from given items of key data.

The Address is calculated with the hashing algorithm and not the data itself. Large data sets can
be organised

Uses:
● Databases - used to create indices for databases enabling quick storage and retrieval of
data.
● Memory addressing: Used to generate memory addresses where data will be stored. E.g
in cache
● Operating Systems: Storage of exe files, programs and utilities.
● Encryption: Used to encrypt data ← hashing algorithm must be complex.
● Checksums.
● Programming: Keywords and identifiers for the compiler.

A simple hashing method:


Address ← key mod (number of slots)

Although this may result in the following problems.

Problems with hash tables -

Collisions - When a hashing algorithm produces the same index for two or more different keys.

Clustering - When a hashing algorithm produces indices that are not randomly distributed.

A hashing algorithm must also be able to generate as many indices are there are elements of
data.
Load factor - The ratio of how many indices are available to how many there are in total. Number
of keys divided by the number of slots.

Fixes for collisions -

Chaining - A technique for generating a unique index when there is a collision by adding the
key/value pair to a list stored at the same index. A linked list can be used.
Rehashing - The process of running the hashing algorithm again when a collision occurs (as an
alternative, another subsidiary hashing algorithm can be used.

4.2.7 Dictionaries
4.2.7.1 Dictionaries
G-Site
Presentation

● Be familiar with the concept of a dictionary.


○ A collection of key-value pairs in which the value is accessed via the associated key.
● Be familiar with simple applications of dictionaries, for example information retrieval, and have
experience of using a dictionary data structure in a programming language.
○ Information retrieval:

For example, the document 'The green, green grass grows' would be represented by the
dictionary:

{‘grass’ : 1, ‘green’ : 2, ‘grows’ : 1, ‘the’ : 1} ignoring letter case.

Dictionary - A data structure that maps keys to data. Also known as an associative array.

The dictionary address for each key:value pair can be calculated using a hashing algorithm - it
most times, is.

Uses:
● In a computer system: ASCII/ Unicode tables.
● In a translation program: foreign language dictionary containing words and meanings.
● Other data structures may be implemented using dictionaries.

Actions:
● Add a new key:value pair to the dictionary
● Delete a key:value pair from the dictionary
● Amend the value in a key:value pair
● Return the value associated with key k
● Return True or False depending on whether the key is in the dictionary
● Return the length of the dictionary

4.2.8 Vectors
4.2.8.1 Vectors
G-Site
Presentation

● Be familiar with the concept of a vector and the following notations for specifying a vector:
○ [2.0, 3.14159, -1.0, 2.718281828].
○ 4-vector over ℝ written as ℝ4.
○ Function interpretation
■ 0 ↦ 2.0
■ 1 ↦ 3.14159
■ 2 ↦ -1.0
■ 3 ↦ 2.718281828
■ ↦ means maps to
○ That all the entries must be drawn from the same field, eg ℝ.
■ A vector can be represented as a list of numbers, as a function and as a way of
representing a geometric point in space.

A dictionary is a useful way of representing a vector if a vector is viewed as a


function.
f:S→ℝ
the set S = {0,1,2,3} and the co-domain, ℝ, the set of Reals

For example, in Python the 4-vector example could be represented as a dictionary


as follows:
{0:2.0, 1:3.14159, 2:-1.0, 3:2.718281828}
● Dictionary representation of a vector.
○ See above.
● List representation of a vector.
○ For example, in Python, a 2-vector over ℝ would be written as [2.0,3.0].
● 1-D array representation of a vector.
○ For example in VB.Net, a 4-vector over ℝ would be written as Dim example(3) As Single.
● Visualising a vector as an arrow.
○ For example a 2-vector [2.0, 3.0] over ℝ can be represented by an arrow with its tail at the
origin and its head at (2.0, 3.0).
● Vector addition and scalar-vector multiplication.
○ Know that vector addition achieves translation and scalar-vector multiplication achieves
scaling.
● Convex combination of two vectors, u and v.
○ Is an expression of the form αu + βv where α, β ≥ 0 and α + β = 1
● Dot or scalar product of two vectors.
○ The dot product of two vectors, u and v,
u = [u1, …., un ] and v = [v1, ….., vn ] is
u ∙ v = u1v1 + u2v2 + …… + unvn
● Applications of dot product.
○ Finding the angle between two vectors.

Vector - A mathematical quantity that has both magnitude (size) and direction.

Vectors can be represented and applied in various ways. Mathematically and geometrically. E.g:
● As a data structure.
● As a method for mapping one value to another
● As a method of defining geometric shapes.

Uses:
● Vector graphics and 3D graphics.
● Computer games / simulations.
● Multiple dimensions.

Vectors can be implemented as values stored in a list.

Representing vectors as a function -


F:S → R
Where:
F = the function to create the vector.
S = the complete set of values that the function can be applied to.
R = the potential outputs of the function.

S = {0, 1, 2, 3} maps to [2.55, -3.88, 4.11, 5.77]


0 ↦ 2.55 Location 0 maps to the value 2.55
1 ↦ -3.88
2 ↦ 4.11
3 ↦ 5.77

Representing vectors as arrows -

2-vector-

3 - vector -

Vector Addition -

Just doing a + b will get the vector in between the two (from 0) - which also happens to be the
co-ordinate.
Scalar-vector multiplication -

In essence multiplying a vector by x amount of times. Increasing the length of that vector by x
amount of times.

Dot product -

A . B = AxBx + AyBy

Above only applies for 2-vectors - The same repetition applies for larger vectors.
Only produces 1 number.

Uses of dot product -


● One vector contains unit prices, another vector contains numbers sold, then the dot
product gives the amount of money taken.
● To determine the amount to vary the light when shading an object.

Convex Combination -

A method of multiplying vectors that produces a resulting vector within the convex hull (grey
space).

w = αu + βv
Where:
● α,β >= 0
● α+β=1

Uses of convex combination -


● 3D modelling - calculating the volume of polyhedra
● Drawing images in perspective (one behind another, hidden line removal.)

Parity bit

Vectors can be used to calculate parity bits with a bitwise AND and XOR combination.

4.3 Fundamentals of algorithms


4.3.1 Graph-traversal
4.3.1.1 Simple graph-traversal algorithms
● Be able to trace breadth-first and depth-first search algorithms and describe typical applications
of both.
○ Breadth-first: shortest path for an unweighted graph.
Depth-first: Navigating a maze.

4.3.2 Tree-traversal
4.3.2.1 Simple tree-traversal algorithms
Recursion

n! = n x (n-1)!

A function calling itself.


A stopping condition or base case must be included which when met means that the routine will
note call itself and will start to “unwind” (or pop off the stack).

A call stack is used to store the return address.

Even with a stopping condition, the recursive routine can only be called a limited number of times
or the stack will overflow the maximum memory capacity.

● Be able to trace the tree-traversal algorithms:


○ Pre-order
○ Post-order
○ In-order.
● Be able to describe uses of tree-traversal algorithms.
○ Pre-Order: copying a tree.
In-Order: binary search tree, outputting the contents of a binary search tree in ascending
order.
Post-Order: Infix to RPN (Reverse Polish Notation) conversions, producing a postfix
expression from an expression tree, emptying a tree.

4.3 Fundamentals of algorithms


4.3.3 Reverse Polish
Video 1
Video 2

4.3.3.1 Reverse Polish – infix transformations


● Be able to convert simple expressions in infix form to Reverse Polish notation (RPN) form and vice
versa. Be aware of why and where it is used.
○ Eliminates need for brackets in subexpressions.
Expressions in a form suitable for evaluation using a stack.
Used in interpreters based on a stack for example Postscript and bytecode.

Infix notation:
A+B
‘ + ‘ part (the notation) is ‘fixed in’ between the operands

2*A+B
is ambiguous

Prefix / Polish Notation:


+AB
(“Add Number A to number B”)
No ambiguity.

Postfix / Reverse Polish Notation:


AB+
(“Take two numbers and add them together.”)

3*(1+2)

Computers are not able to evaluate this logic.

In a computer using RPN: 312+*


Get it by using post-order traversal.
A stack is able to be created from this and used to compute the answer.
Used in interpreters based on a stack for example Postscript and bytecode

4.4 Theory of Computation


4.4.1 Abstraction and automation -
Document (even though all my notes are here)

4.4.1.1 Problem-solving (AS)


Presentation
● Be able to develop solutions to simple logic problems.
● Be able to check solutions to simple logic problems.

4.4.1.2 Following and writing algorithms (AS)


● Understand the term algorithm.
Algorithm - A sequence of steps that can be followed to complete a task and that always
terminates.
○ A sequence of steps that can be followed to complete a task and that always terminates

● Be able to express the solution to a simple problem as an algorithm using pseudo-code, with the
standard constructs:
○ Sequence
For loop
○ Assignment
Variable declaration/ assignment
○ Selection
If statement
○ Iteration.
While loop

● Be able to hand-trace algorithms.


Trace tables for loops.

● Be able to convert an algorithm from pseudocode into high level language program code.

All of the above is self explanatory

● Be able to articulate how a program works, arguing for its correctness and its efficiency using
logical reasoning, test data and user feedback.

4.4.1.3 Abstraction (AS)


Presentation

● Be familiar with the concept of abstraction as used in computations and know that:
○ Representational abstraction is a representation arrived at by removing unnecessary
details
○ Abstraction by generalisation or categorisation is a grouping by common characteristics
to arrive at a hierarchical relationship of the 'is a kind of' type.

Explains itself.

4.4.1.4 Information hiding (AS)


Presentation

● Be familiar with the process of hiding all details of an object that do not contribute to its essential
characteristics.

4.4.1.5 Procedural abstraction (AS)


Presentation

● Know that procedural abstraction represents a computational method.


○ The result of abstracting away the actual values used in any particular computation is a
computational pattern or computational method - a procedure.

Writing procedures and passing parameters so that variables are locally stored and taken away
from the main program.

4.4.1.6 Functional abstraction (AS)


Presentation

● Know that for functional abstraction the particular computation method is hidden.
○ The result of a procedural abstraction is a procedure, not a function. To get a function
requires yet another abstraction, which disregards the particular computation method.
This is functional abstraction.

Using a function does not need specific details on how the computation works, only information
on how to call the function and then what parameters to pass - and therefore that is the ‘further
abstraction’.

4.4.1.7 Data abstraction (AS)


Presentation

● Know that details of how data are actually represented are hidden, allowing new kinds of data
objects to be constructed from previously defined types of data objects.
○ Data abstraction is a methodology that enables us to isolate how a compound data
object is used from the details of how it is constructed.
○ For example, a stack could be implemented as an array and a pointer for top of stack.

4.4.1.8 Problem abstraction/reduction (AS)


Presentation
● Know that details are removed until the problem is represented in a way that is possible to solve,
because the problem reduces to one that has already been solved.

4.4.1.9 Decomposition (AS)


Presentation
● Know that procedural decomposition means breaking a problem into a number of sub-problems,
so that each sub-problem accomplishes an identifiable task, which might itself be further
subdivided.

4.4.1.10 Composition (AS)


● Know how to build a composition abstraction by combining procedures to form compound
procedures.
● Know how to build data abstractions by combining data objects to form compound data, for
example tree data structure.

4.4.1.11 Automation (AS)


Presentation
● Understand that automation requires putting models (abstraction of real world objects/
phenomena) into action to solve problems. This is achieved by:
○ Creating algorithms
○ Implementing the algorithms in program code (instructions)
○ Implementing the models in data structures
○ Executing the code.
■ Computer science is about building clean abstract models (abstractions) of messy,
noisy, real world objects or phenomena. Computer scientists have to choose what
to include in models and what to discard, to determine the minimum amount of
detail necessary to model in order to solve a given problem to the required degree
of accuracy.
■ Computer science deals with putting the models into action to solve problems. This
involves creating algorithms for performing actions on, and with, the data that has
been modelled.
Abstraction Worksheet 1 -

Stacks and Queues:


https://www.youtube.com/watch?v=idrrIMXXeHM

Q1-
An algorithm is to be written to find the shortest route between two points. How can
abstraction be applied to this problem?
What applications could such a program be useful for?

Abstraction can be applied by finding parts of code which extend the distance between the two
points or unneeded bits of coding that make the program function irregularly. The most significant
variables can be put into a stack or procedural abstraction can be used to allow for the inputting
of the parameters and sorting in subroutines.

Aircraft routing, GPS systems - navigation systems in general.

Q2 -
Give examples of some problems which can be “solved” by computer simulations

Virtual viewings of buildings. Crime scene rebuilding. Some simulations of trajectories can be
visualised as well as graphing quickly can be solved and previewed easily with computer
programs.

Q3 -
What factors would be relevant in a financial model which calculates the likely annual profit
in a new coffee shop?

What factors would be irrelevant?

The parameters given to the code by the user - such as price of coffee, number sold, cost of
supplies/ resources/ bills/ tax, etc. Other things that allow for the calculations to happen and the
structuring of the code would also be relevant in the program.

Irrelevant factors would be things such as colour of coffee cup or variables such as that. As well
as environmental factors such as weather.

Q4-
You have been asked to write a procedure to count the number of vowels in a sentence.
How can you ensure that the procedure will work for any length of sentence?

Make an open, unlimited length capable array and treat is like a stack. Append each character
within the sentence to the array and check for ‘a’,’e’,’i’,’o’ or ‘u’. This will work for any length of
sentence.

Q5 -
To implement a stack, you would need three procedures: InitialiseStack(stack, pointer),
AddToStack(stack, pointer, item), RemoveFromStack(stack, pointer, item).
The identifiers in brackets are parameters defined in the main program and passed to the
Procedure.

What procedures and parameters would you need to be able to implement a queue?

InitialiseQueue(queue, frontelement, lastelement)


(Offer also means Enqueue)
EnQueue(queue, lastelement, item)
(Poll also means Dequeue)
DeQueue(queue, frontelement, item)

Q6-
A car dealer might use a procedure for displaying different models of a particular make of
car. The user can specify what model they are interested in, how many doors the car
should have, the paint colour, wheels, and interior specifications.
See http://www.volkswagen.co.uk/configurator
Draw a hierarchy chart to show how the procedure for displaying a particular model might be
broken down into separate tasks and subtasks.
What type of abstraction is being used in this problem?

Procedural Abstraction is being used as procedures are utilised accepting human inputs in them.

4.4.2 Regular Languages


4.4.2.1 Finite state machines (FSMs) {with and} without output {AS}
Presentation
Worksheet
C&DVideo
● Be able to draw and interpret simple state transition diagrams and state transition tables for
FSMs with no output and with output (Mealy machines only).

Finite State Machine -


A model of computation, used for describing and designing. Any device that stores its current
status and whose status can change as the result of an input.

Can only be at one state at a time.

Accept(ing) State -
The state that identifies whether an input has been accepted.
● Possibly one or more.
● Usually double circles.

Transition Arrows -
● Join Transitions, allowing movement
● Directional arrows

Transition Condition -
● Each arrow must have a condition.
● This is the input which causes a move in states. (Following the direction of the arrow)
● 0,1 means 0 or 1 accepted.

State Transition Table -

Mealy Machine -
A finite state machine with an output.
● Outputs are determined by both: current state and current input.
● As with standard FSM for each given state and input there can only be one possible
transition.
4.4.2.2 Maths for regular expressions
Link
● Be familiar with the concept of a set and the following notations for specifying a set:

A = {1, 2, 3, 4, 5 }

or set comprehension:

A = {x | x ∈ ℕ ∧ x ≥ 1 }

where A is the set consisting of those objects x such that x ∈ ℕ and x ≥ 1 is true.

Know that the empty set, {}, is the set with no elements.

Know that an alternative symbol for the empty set is Ø.

○ A set is an unordered collection of values in which each value occurs at most once.

Several languages support set construction.

In Python, for example, use of curly braces constructs a set:


{1, 2, 3 }.

| means such that.

x ∈ ℕ means that x is a member of the set ℕ consisting of the natural numbers, ie {0, 1, 2,
3, 4, … }.

The symbol ∧ means AND.

The term ∧ x > = 1 means AND x is greater than or equal to 1.

In Python, {2 ∗ x for x in {1, 2, 3 }} constructs {2, 4, 6 }.

This is said to be a set comprehension over the set {1, 2, 3 } .


● Be familiar with the compact representation of a set, for example, the set {0n1n | n ≥ 1}. This set
contains all strings with an equal number of 0 s and 1s.
○ For example,
{0n1n | n ≥ 1} = {01, 0011, 000111, 00001111, … }

● Be familiar with the concept of:


○ Finite sets
○ Infinite sets
○ Countably infinite sets
○ Cardinality of a finite set
○ Cartesian product of sets.
● A finite set is one whose elements can be counted off by natural numbers up to a particular
number, for example as:

1st element, 2nd element, …, 20th (and final) element.

The set of natural numbers, ℕ and the set of real numbers, ℝ are examples of infinite sets.

A countably infinite set is one that can be counted off by the natural numbers.

The set of real numbers is not countable. The cardinality of a finite set is the number of elements
in a set. Cartesian product of two sets, X and Y, written X x Y and read 'X cross Y', is the set of all
ordered pairs (a, b) where a is a member of A and b is a member of B.

● Be familiar with the meaning of the term:


○ Subset
○ Proper subset
○ Countable set.
■ {0, 1 , 2 } ⊂ ℕ where ⊂ means proper subset of, that is ℕ contains everything in {0,
1, 2 } but there is at least one element in ℕ that is not in {0, 1, 2 }.

{0, 1 , 2 } ⊆ {0, 1, 2, 3 } where ⊆ means subset of.

⊆ includes both ⊂ and =, for example {0, 1, 2, 3 } ⊆ {0, 1, 2, 3 } is also true, because

{0, 1, 2, 3 } = {0, 1, 2, 3 }. A countable set is a set with the same cardinality (number of
elements) as some subset of natural numbers.
● Be familiar with the set operations:
○ Membership
○ Union
○ Intersection
○ Difference.
■ The set difference A\B (or alternatively A-B) is defined by
A\B = {x : x ∈ A and x ∉ B}.
Where a set is finite it has cardinality, meaning that it can be counted using natural numbers.
Cardinality - The number of elements in a set.
Countably infinite sets - Sets where the elements can be put into a one-to-one correspondence
with the set of natural numbers.
Difference - describes which elements differ when two sets are joined together
Proper subset - Where one set is wholly contained within another and the other set has additional
elements.

4.4.2.3 Regular expressions


● Know that a regular expression is simply a way of describing a set and that regular expressions
allow particular types of languages to be described in a convenient shorthand notation.
○ For example, the regular expression a(a|b)* generates the set of strings {a, aa, ab, aaa,
aab, aba, …}.

● Be able to form and use simple regular expressions for string manipulation and matching.
○ Students should be familiar with the metacharacters:
○ * (0 or more repetitions)
○ + (1 or more repetitions)
○ ? (0 or 1 repetitions, ie optional)
○ | (alternation, ie or)
○ ( ) to group regular expressions. Any other metacharacters used in an exam question will
be explained as part of the question.

● Be able to describe the relationship between regular expressions and FSMs.


○ Regular expressions and FSMs are equivalent ways of defining a regular language.
● Be able to write a regular expression to recognise the same language as a given FSM and vice
versa.
○ A student's ability to write very simple regular expressions and FSMs will be assessed.

Regular Expression Meaning Strings Produced

a|b|c a or b or c a
b
c

abc a and b and c abc

a*bc Zero or more a followed by b and c bc


abc
aabc
aaabc
...

(a|b)c a or b and c ac
bc

a+bc One or more a and b and c abc


aabc
aaabc
...

ab?c a and either zero or one b and c ac


abc

Dont need to know -


Searching Strings:

Expression Definition Example

. Effectively a wildcard and matches any .ole would match to mole, hole, vole,
character etc.

[] Matches to a single character within [mh]ole would match mole and hole but
the brackets not vole.

[^] Matches to any character except those [^m}ole would match hole and vole but
in brackets not mole.

* Matches the preceding characters m*ole would match ole, mole, mmole,
zero or more times mmmole, etc.

[m,n] Matches the preceding character at a[2,5] would match aa, aaa, aaaa, and
least m but not more than n times aaaaa.
2 a’s to 5 a’s inclusive of both 2 and 5

4.4.2.4 Regular language


● Know that a language is called regular if it can be represented by a regular expression.
○ Also, a regular language is any language that a FSM will accept.
Regular Language - Any language that can be described using regular expressions.
Regular Expressions contain strings of characters that can be matched to the contents of a set
allowing you to find patterns in data.
Regular Expression - Notation that contains strings of characters that can be matched to the
contents of a set.
There is also a relationship between RE and FSMs in that all REs can be expressed as state
transition diagrams for an FSM and vice versa.
4.4.3 Context-free languages
Context-free language - an unambiguous way of describing the syntax of a language useful
where the language is complex.
For instance it is not possible to define a palindrome in a regular expression.

Where counting and matching is infinite, a context-free language is needed. Context-free


languages can also support notation for recursion and are sometimes a clearer way of defining
syntax even where regular expressions can be used.

4.4.3.1 Backus-Naur Form (BNF)/syntax diagrams


● Be able to check language syntax by referring to BNF or syntax diagrams and formulate simple
production rules.
● Be able to explain why BNF can represent some languages that cannot be represented using
regular expressions.

Backus-Naur Form (BNF) - A form of notation for describing the syntax used by a programming
language.
Set - A collection of symbols in any order that do not repeat.
Terminal - in BNF, it is the final element that requires no further rules.

Syntax Diagram - A method of visualising rules written in BNF or any other context-free language.

BNF -

<S> ::= <alternative1> | <alternative2> | <alternative3>


<alternative1> ::| <alternative2> | <alternative4>
<alternative4> ::| terminal

BNF produces a set of acceptable strings, which effectively describe the rules of the language.

● each symbol or element is enclosed within angle brackets <>


● the ::= means ‘is replaced with’ and defines the rule for the symbol
● each symbol needs to be split down further until you reach a terminal.

To define integers, a BNF expression may look like this:

<integer> ::= <digit> | <digit> <integer>


<digit> ::= 0|1|2|3|4|5|6|7|8|9

This shows that an integer is defined as either a digit or a digit followed by another integer.
A digit ends on a terminal; numbers 0 to 9 as there is no further rule needed to define digits.
This expression would be recursive.

Syntax Diagrams -
Map directly to BNF.

Syntax diagrams are modular so there are likely to be many diagrams required to represent a
whole language.

Another example
4.4.4 Classification of algorithms
4.4.4.1 Comparing algorithms
● Understand that algorithms can be compared by expressing their complexity as a function
relative to the size of the problem. Understand that the size of the problem is the key issue.

● Understand that some algorithms are more efficient:


○ Time-wise than other algorithms
○ Space-wise than other algorithms.
■ Efficiently implementing automated abstractions means designing data models
and algorithms to run quickly while taking up the minimal amount of resources
such as memory.
4.4.4.2 Maths for understanding Big-0 notation
● Be familiar with the mathematical concept of a function as a mapping from one set of values, the
domain, to another set of values, drawn from the co-domain, for example ℕ → ℕ.

● Be familiar with the concept of:


○ A linear function, for example y = 2x
○ A polynomial function, for example y = 2x2
○ An exponential function, for example y = 2x
○ A logarithmic function, for example y = log10 x.
● Be familiar with the notion of permutation of a set of objects or values, for example, the letters of a
word and that the number of permutations of n distinct objects is n factorial (n!).
○ n! is the product of all positive integers less than or equal to n.

4.4.4.3 Order of complexity


● Be familiar with Big-O notation to express time complexity and be able to apply it to cases where
the running time requirements of the algorithm grow in:
○ Constant time
○ Logarithmic time
○ Linear time
○ Polynomial time
○ Exponential time.

● Be able to derive the time complexity of an algorithm.

4.4.4.4 Limits of computation


● Be aware that algorithmic complexity and hardware impose limits on what can be computed.

4.4.4.5 Classification of algorithmic problems


● Know that algorithms may be classified as being either:
○ Tractable – problems that have a polynomial (or less) time solution are called tractable
problems.
○ Intractable – problems that have no polynomial (or less) time solution are called
intractable problems.
■ Heuristic methods are often used when tackling intractable problems.

4.4.4.6 Computable and non-computable problems


● Be aware that some problems cannot be solved algorithmically.

4.4.4.7 Halting problem


● Describe the Halting problem (but not prove it), that is the unsolvable problem of determining
whether any program will eventually stop if given particular input.

● Understand the significance of the Halting problem for computation.


○ The Halting problem demonstrates that there are some problems that cannot be solved
by a computer.
4.4.5 A model of computation

3.4.1.5 Procedural Abstraction -

Procedural abstraction is used to keep the actual values used in a computation separate from the
overall design.

This involves writing procedures and passing parameters.

• Procedural abstraction is used to keep the actual values used in a computation separate from the
overall design

• In simple terms, this involves writing procedures and passing parameters (parameter is an input
variable used in a subroutine, which refers to a piece of data.)

• A car dealer might use a procedure for displaying a particular model of a car, and pass parameters
for colour, number of doors, wheels etc.

3.4.1.6 Functional Abstraction -

The result of a procedural abstraction is a procedure, not a function. To acquire a function


requires another abstraction.

A function is used to stop the need to reuse a line of code/many to ‘calculate a square root’ or
‘generate a random number’

3.4.1.6 Data Abstraction -

Data that is key to solving the program is kept within an abstract data structure - array, stack or
queue.

A stack could be implemented as an array and a pointer for the top of stack.

You might also like