0% found this document useful (0 votes)
20 views

Computer Science

This document discusses different types of data representation in computer science, including user-defined data types, non-composite data types, composite data types, enumerated data types, pointer data types, file organization methods, and file access methods. User-defined types allow programmers to create custom data types to meet the needs of their programs. Common file organization methods include serial, sequential, and random access, each suited to different access patterns. File access can be done sequentially by reading records in order, or directly by using an index to jump to a specific record.

Uploaded by

Faisal Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Computer Science

This document discusses different types of data representation in computer science, including user-defined data types, non-composite data types, composite data types, enumerated data types, pointer data types, file organization methods, and file access methods. User-defined types allow programmers to create custom data types to meet the needs of their programs. Common file organization methods include serial, sequential, and random access, each suited to different access patterns. File access can be done sequentially by reading records in order, or directly by using an index to jump to a specific record.

Uploaded by

Faisal Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

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

13| Data Representation


User-Defined Data Types
Show understanding of why user-defined types are necessary

a data type based on an existing data type or other data types that have been defined by a
programmer

Can be divided into: Non-composite and composite data types

Pros

When there’s no suitable data type is provided by the language used

Programmer needs specify a new data type that meets the requirement of the
program

Ability to self-document user data structures

Let’s user to group data of different types in a single variable

Cons

Computer Science 1
Only possible if a programming language offers support for the construct

Define and use non-composite types

a single data type that does not reference any other data type

Ex: Integer, Real, String, Char, Pointer

Used for a special purpose

Enumerated Data Type (EDT)

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 STRING must be a character in the UNICODE acceptable list

a USER-DEFINED data type be within the user-defined list of prescribed values

Enumerated values are ORDINAL meaning they have a specific order

Allows for comparison statement

Pointer Data Type (PDT)

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

Arithmetic can be performed on pointer variables

Used to contract dynamically varying data structures

Cons

Not all programming languages offer support for the use of PDT

If they do, might have their own symbols

Define and use composite data types

data type constructed from other data types

Computer Science 2
Set Data Type

Allows a program to create sets and to apply the mathematical operations defined in
set theory

A set is mathematical concept with important properties

Contains a collection of data values

No organisation of the data value within the set

Duplicate values are not allowed

Class/Object Data Type

Is a data type which is used is used for an object-oriented programming

There are likely to be a number of built in classes

Record Data Type

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

Enumerated Data Type

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

Pointer Data Type

DECLARE MyPointer : TMyPointer


TYPE
TMyPointer = ^<Type Name>
ENDTYPE

File Organisation and Access


File Organisation

Information is all stored as data in files, hence everything need to be organised

Computer Science 3
data of all types is stored as records in files

Organised using different methods: Serial, Sequential, Random

Show Understanding of the methods of file organisation and select an appropriate method of
file organisation and file access for a given problem

Serial File Organisation

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

Used for real time processing

Do not be sorted, hence making serial files efficient

Sequential File Organisation

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

To allow sequential file to be ordered:

Has to be key field for which the values are unique and sequential

Not necessary consecutive

When a new record added

Append the record, with the intention of sorting the file later

In a sequential file, a particular record can be found by reading all of the


key fields until you reach the one you're looking for

Random File Organisation

records of data are physically stored in a file in any available position

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

Show understanding of methods of file access

File Access

the method used to physically find a record in the file

After file organisation has been chosen, data been entered into a file

You need to consider how this data can be accessed

Sequential access and Direct Access

Sequential Access

Each record in the file is read, one by one, until the desired record is found

Efficient when every record in the file needs to be processed

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

jump to a specific record in the file without accessing other records

Required when only an individual record from a file need to be processed

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

Reading a record from a file using direct access

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)

Floating-Point Numbers, Representation, and Manipulation


Describe the format of binary floating-point real numbers

A binary number written in the form M x 2^E (where M is the Mantissa and E is the
exponent)

A floating-point number consists of three parts:

the sign bit

the mantissa = the fractional part of a floating point number

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

Mantissa must start with 0.1

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

Mantissa must start with 1.0

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

Show understanding of the consequences of a binary representation only being an


approximation to the real number it represents (in certain cases)

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

14| Communication and Internet Technologies


Protocols
Show understanding of why a protocol is essential for communication between computers

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

allows communication between devices operating on different platforms

Show understanding of how protocol implementation can be viewed as a stack, where each
layer has its own functionality

A protocol suite can be represented as a layered structure

Each layer operates independently

Each layer can only communicate with an adjacent layer

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

Show understanding of the TCP/IP protocol suite

a layered stack with 4 layers

uses a set of protocols for transmission of data transport control protocol with internet
protocol

TCP

To only allow data to be sent when the line is idle

To detect a collision on the network

To halt transmission when a collision occurs

IP

Allows applications to exchange data

Computer Science 15
Establish and maintain a connection until exchange of data is complete

4 layer structure

Application Layer

handles access to services

manages data exchange

defines protocols used

HTTP, FTP, POP3, SMTP

Transport Layer

handles forwarding packets

Check packet port to identify the application type

Check packet destination so the packet can be sent to the correct application

Recalculate checksum of packet to ensure integrity

If checksum invalid, it’ll send a message to resend packet

TCP

Internet/Network Layer

Handles transmission of data/routing/IP addressing

IP

Network Access/Data-Link Layer

handles how data is physically sent

Application

1. Messages are split up into packets (APP)

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)

7. Ensure correct routing of packets of data over the internet/network (I/N)

8. Responsible for protocols when communicating between networks (I/N)

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

Hypertext Transfer Protocol (HTTP)

Defines the format of the messages sent and received

browsing websites

used for transfer of web wages from server to client

Underpins the World Wide Web

Used when fetching an HTML document from a web server

File Transfer Protocol (FTP)

to directly transfer data betwee 2 computer over a network

upload and download files over the internet

Used for interactive file transfer

Post Office Protocol 3 (POP3)/Internet Message Access Protocol (IMAP)

used when receiving emails from the email server

mail is held for you by a remote server until you download it

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

Doesn’t keep the server and client in synchronisation

When emails are downloaded by the client, they are then deleted from the server

Simple Mail Transfer Protocol (SMTP)

used for sending email messages

used by mail servers to forward email messages

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

Doesn’t handle binary files: media, images, music

Need to use Multipurpose Internet Mail Extension (MIME) protocol

BitTorrent

protocol which is based on the peer-to-peer networking

Decentralised distribution of data

Allows for very fast sharing of files between computers

keywords

Tracker

Central server that stores details of other computers that have the file to be
downloaded

Seed

Peer computer that has 100% of the file

Swarm

Computer Science 18
All the connected peer computers that have all or part of the file to be
uploaded to the torrent

Steps:

1. client software made available to friends and family

2. a complete copy of the torrent is shared

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

5. The computer can now download the Torrent

6. Once a computer has a piece of the file, it can become a seed and upload it to the
other members

Circuit Switching and Packet Switching


Show understanding of circuit switching

a type of communications in which a dedicated channel or circuit is established for the


duration of a transmission

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

this lasts for the duration of the call

then the links that makes up the circuit are removed

Pros

A dedicated channel

can use all bandwidth

2 way real time conversation

no delay as there’s no switching

Cons

bandwidth/channel may not be available for others

Failure of the single route means failure of the transmission

Show understanding of packet switching

is connected through many routers

Computer Science 19
Features

A circuit that does not have to be established at the start of the communication

data is sent in divided packets

can travel along different routes

packets are reassembled in the correct order at the receiver’s end

Steps

1. A large message is divided up into a group of smaller chunks of the same size called
packets

2. The packet contains a header and payload

3. The header contains a source of IP address and destination IP address

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

6. If packets are missing/corrupted, a re-transmission request is sent

Pros

transmission errors an be detected

packets can be rerouted if there’s a problem

It is possible to overcome failed or faulty lines by simply rerouting packages

doesn’t matter if data arrives out of order

Time delay is insignificant

Cons

Packets can be dropped/delayed

the protocols for packet switching can be more complex than those for circuit
switching

Does not work well with real-time data streams

Comparison

Computer Science 20
15| Hardware and Virtual Machines
Processors, Parallel Processing, and Virtual Machines
Reduced Instruction Set Computer (RISC)

a single instruction is simpler, requiring minimal loading of data from memory

Complex Instruction Set Computer (CISC)

a single instruction can be more complex and involve more loading of data from memory

RISC vs CISC

many instruction formats are possible uses fewer instruction formats/sets

there are more addressing modes uses fewer addressing modes

make use of multi-cycle instruction make use of single-cycle instructions

instructions can be a variable length instructions are a fixed length

longer execution time for instruction faster execution time for instructions

decoding of instructions is more complex makes use of general multi-purpose registers

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

uses the memory unit to allow complex instructions


processor chips require fewer transistors
to be carried out

Pipelining

Computer Science 21
allows several instructions to be processed simultaneously without having to wait for
previous instructions to finish

Stages

1. Instruction Fetch Cycle (IF)

2. Instruction Decode Cycle (ID)

3. Operand Fetch Cycle (OF)

4. Instruction Execution Cycle (IE)

5. Write back Result Process (WB)

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

With pipelining, a new instruction is fetched every clock cycle

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

In pipelining, there is an added complexity; as the interrupt is received, there could be a


number of instructions still in the pipeline

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

2. Contents of the 5 stages can be stored in registers

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

Single Instruction Single Data (SISD)

Computer Science 22
uses a single processor and one data source

Not allow parallel processing due to using 1 processor

E.g. early personal computers

Single Instruction Multiple Data (SIMD)

uses many processors and different data inputs

Each processor executes the same instructions but use different data inputs

Known as array processor

E.g. sound sampling

Multiple Instruction Single Data (MISD)

Computer Science 23
uses many processors but the same shared data source

Each processor uses different instructions but uses the same shared data source

E.g. American Space Shuttle flight control system

Multiple Instruction Multiple Data (MIMD)

use a separate data source

Each one can take its instructions independently, and each processor can use data
from a separate data source

E.g. Multicore systems

Parallel Computer Systems

a number of computers (containing SIMD processors) can be networked together to form a


cluster

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

an emulation of an existing computer system

a computer OS running within another computer’s OS

Give examples of the role virtual machines

Guest Operating System

Computer Science 24
this is the OS running in a virtual machine

controls the virtual hardware during the emulation

OS is being emulated within host OS

Guest OS is running under control of the host OS software

Host Operating System

this is the OS that is controlling the actual physical hardware

it is the normal OS for the host/physical computer

OS runs/monitors the virtual machine software

Understand the benefits and limitations of virtual machines

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

Complex to manage and maintain

Boolean Algebra and Logic Circuits


Produce truth tables for logic circuits including half adders and full adders

Combination Circuits = the output depends entirely on the input values

Half Adder Circuit

carries out binary addition on 2 bits giving sum and carry

Computer Science 26
Full Adder Circuit

two half adders combined to allow the sum of several binary bits

Show understanding of a flip-flop (SR,JK)

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

consist of 2 cross-coupled NAND or NOR gates

Issues:

Invalid S, R conditions (leading to conflicting output values) need to be


avoided

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:

Used to produce shift registers in a computer

A simple binary counter can be made by linking up several JK flip-flop circuits


(this require the toggle function)

Draw a logic circuit and derive a truth table for a flip-flop

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)

Understand De Morgan’s laws

Perform Boolean Algebra using De Morgan’s laws

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

Solve logic problems using Karnaugh maps

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

Flash Memory split into 2 parts:

The part where OS resides (read only)

OS can only be updates by manufacturer but the user cannot interfere with the
software from the memory

The part where apps (and associated data) are stored

User doesn’t have direct access to this part of memory

Show understanding of how an OS can maximise the use of resources

CPU

involves the concept of scheduling to allow for better utilisation of CPU time and
resources

Scheduling = process manager which handles the removal of running programs


from the CPU and the selection of new processes

Memory

the Input/Output (I/O) System

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

DMA initiates data transfer

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

the for of an OS with control over process management, memory management,


interrupt handling, device management, and I/O operations

Computer Science 38
Important task: hide the complexities of the hardware from the users

Using GUI interfaces rather than CLI

Using device drivers (which simplifies the complexity of hardware interfaces)

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’

Show understanding of process management

The concept of multitasking and a process

Multitasking

Function allowing a computer to process more than one task/process at a time

Each of these process will share common hardware resources

To ensure multitasking operates correctly, scheduling is used to decide which


process should be carried out

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

The type of scheduling in which a process switches from running state to


steady state or from waiting state to steady state

Non-preemptive

Type of scheduling in which a process terminates or switches fro a


running state to a waiting state

Comparison

Computer Science 39
Process

a program that has started to be executed

Process Priority depends on:

Category (batch, online, or real time process?)

Whether the process is CPU-bound or I/O bound

Resource equipments (which resources does the process require and how
many)

Turnaround time, waiting time, and response time for the process

Whether the process can be interrupted during running

Once the task/process has been given priority, it can still be affected by:

Deadline for the completion of the process

How much CPU time is needed

Wait time and CPU time

The process states: running, ready, blocked

Process Control Block (PCB)

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

Context switching is used to save the state of pre-empted processes

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

First Come First Served

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

Shortest Remaining Time

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

the core of an OS with control over process management, memory


management, interrupt handling, device management, and I/O operations

Interrupt Dispatch Table (IDT)

Data structure used to implement an interrupt vector table

Interrupt Priority Levels (IPL)

values given to interrupts based on values 0-31

Steps:

1. Interrupt received; other interrupts are then disabled so that the process that deals
with the interrupt cannot itself be interrupted

a. Interrupts will be prioritised using “Interrupt Priority Levels (IPL)”

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

2. The state of the current task/process is saved on the kernel stack

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

3. The source of the interrupt is identified

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

Show understanding of virtual memory, paging, segmentation for memory management

The concept of paging, virtual memory, and segmentation

Paging

form of memory management which divides up physical memory and logical


memory into fixed-size memory blocks

Physical Memory = main/primary RAM memory

Logical Memory = the address space that an OS perceives to be main storage

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

It leads to more efficient multi-programming with less I/O loading and


swapping programs into and out of memory

Computer Science 45
No waste of memory with data that is not being used (e.g. during error
handling)

Eliminates external and internal fragmentation

Removes the need to but more expensive RAM memory

Drawbacks:

as main memory fills, more and more data/pages need to be swapped in and
out of virtual memory

Leads to a high rate of hard disk/write head movements (disk thrashing)

Segmentation

variable size memory blocks into which logical memory is split up

The difference between paging and segmentation

How pages can be replaced

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

Page Fault = a type of interrupt raised by hardware

When a running a program accesses a page that is mapped into virtual


memory address so Cae, but not yet loaded into physical memory, then
the hardware needs to raise this page fault interrupt

First In First Out (FIFO)

the OS keeps track of all pages in memory using a queue structure

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

Suffers from Belady’s Anomaly

a situation in which it is possible to have more faults when increasing the


number of page frames

Optimal Page Replacement (OPR)

looks forward in time to see which frame it can replace in the event of a page
fault

impossible to implement at the time of a page fault, the OS has no way of


knowing when each of the pages will be replaced next

Free of Belady’s anomaly and has the fewest page faults

Least Recently Used Page Replacement (LRU)

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

Clock Page Replacement/Second-Chance Page Replacement

Computer Science 47
use a circular queue structure with a single pointer serving as both head and
tail

When a page fault occurs, the page pointed to is inspected

The action taken next depends on the R-Flag status

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

Page replacement is done by swapping pages from back-up store to main


memory (and vice versa)

If the page to be removed has been modified while in memory, it must be


written back to disk

If it has not been changed, then no re-write needs to be done

How disk thrashing can occur

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

Thrashing can be reduced by

Installing more RAM

Reducing the number of programs running at a time

Reducing size of the swap file

Translation Software
Show understanding of how an interpreter can execute programs without producing a
translated version

Interpreter

Interpreter executes the program its interpreting

The program source code is similarly input

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 construct a symbol table

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

Compiler does not execute the program its compiling

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

Will construct a symbol table

Show understanding of the various stages in the compilation of a program

Lexical Analysis

the first stage in the process of compilation

removes unnecessary characters and tokenized the program

Before translation, the source programs need to be converted to tokens (Tokenization)

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 second stage in the process of compilation

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

The compilation process will finish after this stage

If the tokenized code is error free, it will be passed to the next stage of compilation,
generating the object code

Code Generation

The third stage in the process of compilation

This stage produces an object program to perform the task defined in the source code

The program must be syntactically correct for an object program to be produced

The object program is in machine-readable form (binary)

It is no longer in the form that is readable for humans

This object program is either:

in machine code that can be executed by the CPU

in an intermediate form that is converted to machine code when the program is


loaded (allow grater flexibility)

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

The linking of several programs to run together

Optimization

The fourth stage in the process of compilation

The creation of an efficient object program

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

a formal method of defining the grammatical rules of a programming language

Show understanding of how Reverse Polish Notation (RPN) can be used to carry out the
evaluation of expressions

A method of representing an arithmetical expression without the use of brackets or special


punctuation

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

Used in hashing algorithm

Asymmetric encryption

Private Key

encryption/decryption key which is only known to the owner of the keys

Used in hashing algorithm

Asymmetric encryption

Plain Text and Cipher Text

Plain Text = the original text/document

Cipher Text = the encryption of bits in sequence as they arrive at the


encryption algorithm

Symmetric Key Cryptography

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

Key has to be exchanged securely

Once compromised the key an be used to decrypt both sent and received
messages

Cannot ensure nonrepudiation

Asymmetric Key Cryptography

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:

1. Both sender and recipient use an algorithm to generate their own


matching pairs of keys (private and public) which they keep stored on their
computers

The matching pairs of keys are mathematically linked but cannot be


derived from each other

2. Recipient sends their public key to sender

3. Sender now uses recipient’s public key to encrypt the document sender
want to send

Sender then sends the encrypted document (cipher text) to recipient

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

Increased message security as one key is private

Allows message authentication

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

4 main security concerns when data is transmitted:

Confidentiality = where only the intended recipient should be able to read or


decipher the data

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

How the keys can be used to send a private message

Purposes, benefits, and drawbacks of quantum cryptography

Quantum Cryptography

cryptography based on the laws of quantum mechanics (the properties of photons)

A more accurate name for it is Quantum Key Distribution (QKD)

Uses Qubit (Quantum Bit) as the unit

Purpose

helps protect the security of data being transmitted over fibre optic cables

Benefits

Any eavesdropping can be identified

Integrity of the key once transferred can be guaranteed

Cannot be copied and decrypted at a later date

Longer/more suckers keys can be exchanged

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)

It is possible for the polarisation of the light to be altered (due to various


conditions) while travelling down fibre optic cables

Due to the inherent security system generated by quantum cryptography, criminals


can use the technology to hide their activities from government law enforcers

Show awareness of the Secure Socket Layer (SSL) / Transport Layer Security (TLS)

Secure Socket Layer (SSL)

security protocol used when sending data over the internet

Transport Layer Security (TLS)

A more up to date version of SSL

Purpose of SSL / 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

Data Compression (reducing the amount of data being transmitted)

Data Integrity checks

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

Use of SSL/TLS in client-server communication

SSL

TCP is used to established a connection between the client and the server

A handshake takes place, thus enabling communication to begin between the


client and 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

To be able to create an SSL connection, a web server requires an SSL digital


certificate; the website owner needs to obtain this certificate to allow SSL
protocols to be used

TLS

Formed of 2 layers:

Handshake Protocol

Uses asymmetric cryptography to generate agreed parameters and


establish a spread session key

The shared session key provides symmetric cryptography for sending and
receiving data (record layer)

Record Protocol

responsible for identifying different types of messages (handshake, alert,


or data via the "Content Type" field)

Secures and verify the integrity of each message

Situations where the use of SSL/TLS would be appropriate

SSL

only the most recent web browsers support both SSL and TLS, which is why the
older, less secure, SSL is still used

TLS

Email

VPN

VOIP

TLS can extend by adding new authentication methods

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

Show understanding of digital certification

Keywords:

Computer Science 57
Digital Certificate

an electronic document used to prove the identity of a website or individual

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

Use public key Only signature uses private key

How a digital certificate is acquired

Applied to an issuing certificate authority (CA) With proof of identity

Name, address

So their identity can be checked by an Organisational Registration Authority (ORA)

A digital certificate will only be issued to a trusted organisation

How a digital certificate is used to produce digital signatures

Message is put through agreed hashing/encryption algorithm to produce a hash


total/message digest

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)

B’s Hashing algorithm is used to produce the message digest

The message digest is then encrypted with B’s private key to provide a DS

Both the encrypted messages and DS are sent

Message is decrypted with A’s private key

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

The branch of computer science that aims to make machines ‘intelligent’

Purpose and structure of a graph

Use A* and Dijkstra’s algorithm to perform searches on a graph

Dijkstra’s Algorithm

An algorithm that finds the shortest path between 2 nodes or vertices in a


graph/network

E.g. GPS tracking

Steps:

1. Give the start vertex a final value of 0

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

Heuristic = method that employs a practical solution (rather than a theoretical


one) to a problem; when applied to algorithms this includes running tests and
obtaining results by trial and error

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

Can recognize complex patterns

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

“Labeling” or predicting unknown value for some piece of data

Computer Science 62
Classification

The unknown value is a category

E.g. Pig or not pig? Cat, dog, or duck?

Models: Decision Tree, Nearest Neighbors, Logistic Regression

Regression

The unknown value is a number

E.g. Price of a house? Height of a tree? Probability of an event?

Models: Linear 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

Discovering “structure” or underlying patterns in a collection of data

E.g. Discovering diseases, finding groups of customers for marketing, exploring


data before you do something else with it

Computer Science 63
Deep Learning

machines that think in a way similar to the human brain

they handle huge amounts of data using artificial neural networks

look at binary pixels of each pixel

excellent at identifying patterns which would be to complex or time consuming for


humans to carry out

e.g. Face recognition

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

Show understanding of back propagation of errors and regression methods in machine


learning

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

Training a network/model is more difficult

Activation is fed forwards until a fixed value is achieved

Regression

Statistical measure used to make predictions from data by finding learning


relationships between the inputs and outputs

19| Computational Thinking and Problem Solving


Algorithm
Show understanding of linear and binary searching methods

Write an algorithm to implement a linear search

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")

Write an algorithm to implement a binary search

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?"))

def binary_search(Pew, low, high, x):


if high >= low:
mid = (high + low) // 2
if Pew[mid] == x:
return mid
elif Pew[mid] > x:
return binary_search(Pew, low, mid - 1, x)
else:
return binary_search(Pew, mid + 1, high, x)
else:
return -1

result = binary_search(Pew, 0, len(Pew)-1, x)


if result != -1:
print("I am here!", "This is how many times I had to execute:", str(result))
else:
print("I am not here!")

The conditions necessary for the use of a binary search

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

3. Calculate the new middle and go back to step 1

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

Write an algorithm to implement an insertion sort

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

while p >= 0 and x<Pew[p]:


Pew[p+1] = Pew[p]
p = p-1
Pew[p+1] = x

Computer Science 67
insertionsort(Pew)
print (Pew)

Write an algorithm to implement a bubble sort

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

different sorting algorithm can be compared using efficiency “big O notation”

Show understanding of and use of Abstract Data Types (ADT)

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 = []

# Adding elements to the queue


queue.append('a')
queue.append('b')
queue.append('c')

print("Initial queue")

Computer Science 69
print(queue)

# Removing elements from the queue


print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))

print("\nQueue after removing elements")


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

# Prints out the linked list in traditional Python list format.


def display(self):
elems = []
cur_node = self.head
while cur_node.next!=None:
cur_node=cur_node.next
elems.append(cur_node.data)
print (elems)

# Returns the value of the node at 'index'.


def get(self,index):
if index>=self.length():
print("ERROR: 'Get' Index out of range!")
return None
cur_idx=0
cur_node=self.head

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)

Changing and Adding Dictionary Elements

# Changing and adding Dictionary Elements


my_dict = {'name': 'Jack', 'age': 26}

Computer Science 72
# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}


print(my_dict)

Removing Elements from Dictionary

# Removing elements from a dictionary

# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, returns its value


# Output: 16
print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove an arbitrary item, return (key,value)


# Output: (5, 25)
print(squares.popitem())

# Output: {1: 1, 2: 4, 3: 9}
print(squares)

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself


del squares

# Throws Error
print(squares)

Binary Tree

from binarytree import Node


root = Node(3)
root.left = Node(6)
root.right = Node(8)

print('Binary tree :', root)


print('List of nodes :', list(root))

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):

# Protect against deleting a node not found in the tree


if node==None or self.find(node.value)==None:
print("Node to be deleted not found in the tree!")
return None

# 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

# returns the number of children for the specified node


def num_children(n):
num_children=0
if n.left_child!=None: num_children+=1
if n.right_child!=None: num_children+=1
return num_children
node_parent=node.parent
node_children=num_children(node)
if node_children==0:
if node_parent!=None:
if node_parent.left_child==node:
node_parent.left_child=None
else:
node_parent.right_child=None
else:
self.root=None

# CASE 2 (node has a single child)


if node_children==1:
if node.left_child!=None:
child=node.left_child
else:
child=node.right_child
if node_parent!=None:
if node_parent.left_child==node:
node_parent.left_child=child
else:

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))

Show how it is impossible for ADTs to be implemented from another ADT

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)

Big O notation to specify time and space complexity

Bubble Sort required temporary memory for only a single data item

Insertion sort used no additional memory

Bubble Sort recognises that the list is completely sorted and will stop

Insertion sort requires that every item is considered

Recursion

Computer Science 76
Show understanding of recursion

Essential features of recursion

How recursion is expressed in a programming language

Write and trace recursive algorithms

When the use of recursion is beneficial

Show awareness of what a compiler has to do to translate recursive programming code

Use of stacks and unwinding

20| Further Programming


Programming Paradigms
Understanding what is meant by programming paradigm

Show understanding of the characteristics of Low-Level programming

Understanding of and ability to write low level code that uses various addressing modes:
immediate, direct, indirect, indexed, and relative

Show understanding of the characteristics of Imperative (Procedural) programming

Assumed knowledge and understanding of Structural Programming

Understanding of and ability to write imperative (procedural) programming code that uses
variables, constructs, procedures, and functions

Show understanding of the characteristics of Object Oriented programming

Understanding of the terminology associated with OOP (including objects, properties,


methods, classes, inheritance, polymorphism, containment (aggregation), encapsulation,
getters, setters, instances)

Understanding of how to solve a problem by designing appropriate classes

Understanding of and ability to write code that demonstrate the use of OOP

Show understanding of the characteristics of Declarative programming

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

File Processing and Exception Handling

Computer Science 77
Write code to perform file-processing operations

Open (in read, write, append mode) and close a file

Read a record from a file and write a record to a file

Perform file-processing operations on serial, sequential, random files

Show understanding of an exception and the importance of exception handling

Know when it is appropriate to use exception handling

Write a program code to use exception handling

Computer Science 78

You might also like