SOFTWARE DEVELOPMENT


Data Structures

Contents

What Are 2D Arrays?

Prior Knowledge: 1D Arrays

From Intermediate, you should have knowledge of a 1D Array, a simple list of entities from the same type.


In this section you need to know what a 2D array is and how to make one.


A 2D Array is an array that has rows and columns, similar to a table of squares (as seen under)

2D Array Depiction

A 2D Array has 2 indexes you can retrieve, the column index and the row index. The column index returns a 1D array at the specified index and the row index returns an item in the array at the specified index.


You Can Create a 2D Array Using the Following Code (Python)

[[i]*cols for i in range(rows)]

You Can Obtain specific items from the array using code similar to below

slicedArray = array[col][row]

Traversing a 2D Array

Prior Knowledge: Loops

Along with knowing how to make 2D Arrays, you also have to be able to traverse them


To traverse a 2D array, you can use a nested loop setup like the below code

for x in range(rows):
  for y in range(cols):
    array[x][y] = random.randint(0, 10)
                      

You can use this concept to print out the array 1 row at a time. When you print out the array outright you get the below output

print(array)
> [[2,7,6,3],[2,7,6,3],[2,7,6,3],[2,7,6,3],[2,7,6,3]]
                      

But by traversing the array, you can either print out each row or each number in the row

# Print Out Each Row
for x in range(rows):
  print(array[x])
                      
# Print Out Each Number In Each Row
for x in range(rows):
  for y in range(cols):
    print(array[x][y])
                      

NOTE: When Using An Array With an Undetermined Length, use the len(array) to get the length instead

Summary

Prior Knowledge: 2D Arrays

To Summarise what you've just learned:

  • 2D Arrays are similar to a grid of squares, each column will return a 1D array of values
  • A 2D Array can be indexed with 2 indices, i.e arr[x][y]
  • You can traverse a 2D array using a nested loop setup

NOTE: This is Theory and there's no code to go with this in AH, but it will come up in the exam

What's a Linked List?

Prior Knowledge: Dynamic List Items (Basic)

A linked list is what's considered a dynamic data structure

  • Linked Lists Store Information in nodes
  • Linked Lists Have No Fixed Size

Linked Lists Are Different To Arrays as Arrays create copies of themselves with the new sizing, which could cause all sorts of memory and processor problems


Nodes

A node is like a box with 3 compartments

  1. Memory Address - The memory address the node is stored at
  2. Data Item - The item of data the node holds
  3. Next Pointer - The memory address of the next node in the list
Single Node Depiction

The start of each list is called the head and the ending nodes next pointer is always null

An Example of a Single Linked List is shown below


Single Node Depiction

Some More Information About Linked Lists

  • A Linked List can store multiple types of data, not being excluded to 1 like arrays
  • A linked list can only be traversed from head to tail (the null pointer node), usually until the data is found
  • Inserting information into a linked list is more efficient than an array because:
    • When inserting or deleting information, only the pointer is changed compared to arrays which shift the information into different memory locations

Insertion of Information Into Linked Lists

To insert new information into a linked list, you need to:

  1. Create a new node in memory
  2. Find the Null Pointer Node
  3. Update the pointers for the null pointer node to point to the new nodes memory location
  4. Set the new nodes pointer to null and add the new information

Deletion of Information Into Linked Lists

To delete information from a linked list, you need to:

  1. find the memory location of the node to delete
  2. Go through the list until you find the node
  3. Update the pointers for the node ahead and behind the deleted node to point to the nearest nodes memory location

Linked List Operations

  • Adding a new node at the end
    • The pointer of the last node will have to point ot the newly created node
  • Inserting Between Exisitng Nodes
    • When the new node is added then the pointer of the top and bottom nodes are changed accordingly
  • Deleting Nodes
    • The point of the previous node before the deleted node is changed to the next node in the list
  • Traversing Lists
    • Each node has been visited and the pointer followed to the address of the next node

What's a Double Linked List?

Prior Knowledge: Dynamic List Items (Basic)

A double linked list is similar to a single linked list but it stores the previous nodes memory position on top of the ahead node

An example of a double linked node is shown below

Single Node Depiction

And below this is an example of a double linked list, showing the connections between each node

Single Node Depiction

Insertion & Deletion of Information is almost identical as in a single linked list but now you have to update the previous node memory locations as well

To Conclude Linked Lists

  • Single
    • Nodes have 3 fields: its memory address, the data held and the memory address of the next node in the list
    • The end nodes next pointer will be null
  • Double
    • Nodes have 4 fields: its memory address, the data held, the mem. addr. of the previous node and the mem. addr. of the next node in the list
    • The start nodes previous node pointer will be null and the end nodes next pointer will be null as well

Advantages & Disadvantages

  • Advantages
    • Linked lists are much more efficient in terms of memory and processing, especially when manipulating data
    • Inserting, deleting or reordering only requires pointer info to change
  • Disadvantages
    • Cannot index a particular node of a single linked list in an array, you have to go through each node item until you find the one you need
    • Requires storing additional info (pointer memory locations)
    • Nodes may not be stored in adjacent areas of RAM

Object Oriented Programming


What Are Classes?

Prior Knowledge: Records, Functions & Procedures

From Intermediate, you should have knowledge on a Record, a simple structure used to help container-ise your project. And on functions & procedures, which allow you to package up sections of code to run in a different part of your program.


In this section you need to know what a class and an object is and how to create and manipulate its properties


A class is difficult to describe so a better way to explain it is to use an example, so lets use the example of a bicycle


All bicycles have the same base attributes and functions, whilst there are different types of bicycles they all share the same base


The same can be said for classes. There can be a base class with attributes and methods used in different subclasses but each subclass can have its own unique set of functions


This is how a class is declared in python

class Bicycle:

You can assign values to a class using an initialisation (or constructor) method, in python this is: def __init__()


Putting this all together, lets add some properties to our bicycle class

class Bicycle:
def __init__(self, bikeGear, bikeSpeed, bikeColor):
  '''This runs when we instantiate a new class instance'''
  self.bikeGear = bikeGear
  self.bikeSpeed = bikeSpeed
  self.bikeColor = bikeColor
                      

Now that we've assigned out values, whenever we instantiate (make a duplicate of) the class, we can assign unique values to these variables and retrieve them when needed, an example is shown below

variable = Bicycle(5, 3, 'Green')
print(variable.bikeColor)
> Green
                      

Now what we've done there is create an instance of the Bicycle class and assigned its variables 3 distinct values, then printed out one of those values to the console to test if it was working as intended.


This instance is called an Object.

Methods... Isn't that Just Functions?

Prior Knowledge: Functions & Procedures

Methods are functions & procedures within classes that can't be called without referring to an instance of that class or the class itself (in very rare circumstances)


There are 3 main methods in classes:

  1. Constructor Methods
  2. Getter Methods
  3. Setter Methods

NOTE: When we get further into this topic, it's useful to know you can override methods


Lets take our bicycle example from below and add some methods to it. Lets add a method to return the current gear and a method to change the gear on the bike

class Bicycle:
# previous code above

def GetGear(self, newGear): return self.bikeGear

def SetGear(self, newGear):
  self.bikeGear = newGear
                      

Now you might be wondering why we're not just setting the gear and speed variables directly, and this is because of something called Encapsulation.


Encapsulation helps limit direct access to (possibly sensitive) variables inside of classes, by using methods such as those above it funnels the usage of these variables to (usually) 2 routes, and those are called getters and setters, denoted most commonly by their 'Set' or 'Get' prefixes on functions or procedures.

Summary

To Summarise the above 2 sections:

  • Classes - A type used to store information specific to an entity. Creating a new copy of the class is called Instantiation
    • Uses - Classes can store both values and functions or procedures, called methods
  • Methods - A method can only be called when using an instance of that class or the class itself
    • Constructor Method - A special method used when a new class instance is made, setting up the unique values for this instance
    • Getters & Setters - Special methods used to block unwanted access to variables within classes
  • Object - An object is an instance of any class and can be stored like a variable

Inheritance? I thought this was a Comp Sci Course

Prior Knowledge: Classes, Objects

In the previous sections we've covered classes and how to make them, we've also covered the 3 main types of methods, there are a few things left to do with classes


When using classes, some classes will end up with similar or identical methods, so to make things cleaner you can have subclasses, that inherit methods from a parent class


Using our example from before, lets create a new subclass called 'MountainBike' that inherits from the base Bicycle class

class MountainBike(Bicycle): # Inherits from Base Class
def __init__(self, bikeGear, bikeSpeed, bikeColor):
  # A way of calling the base class constructor
  super().__init__(bikeGear, bikeSpeed, bikeColor)
                      

And now when we initialise the MountanBike subclass by default it'll ask us to provide it with values for the 3 variables in the parent Bicycle class. The MountainBike subclass will also have the same methods as the parent class, those being 'GetGear' and 'SetGear'.

Polywhatsit?

Prior Knowledge: Classes, Objects, Inheritance

Finally, for the coding part. There's polymorphism. Polymorphism is a key term used to describe when classes have the same methods that do different things, also known as overridden methods. This follows on from inheritance by changing a base methods programming.


For example, lets say our Bicycle class had a method that calculated distance based on wheel turns per minute

class Bicycle:
def CalculateSpeed(self, wheelturns): 
return self.bikeSpeed * wheelturns
                      

And out MountainBike subclass had the same method but calculated distance based on the force exerted on the pedals per minute

class MountainBike(Bicycle):
def CalculateSpeed(self, pedalPressure): 
return self.bikeSpeed * pedalPressure
                      

Or If you're simply changing the variable used, you can use the below code (A bit more advanced)

class MountainBike(Bicycle):
def CalculateSpeed(self, pedalPressure):
return super().CalculateSpeed(pedalPressure)
                      

That's polymorphism. 2 of the same methods, but the subclass method is different to the base class method.

Summary

To Summarise:

  • Inheritance - A subclass can inherit variables and methods from a base/parent class
  • Polymorphism - A subclass can override methods and variables which allows for 2 of the same method to do different things

There's More Standard Algorithms?!

Prior Knowledge: Intermediate Algorithms

Yep, 3 more in AH. Those Are:

  • Insertion Sort
  • Bubble Sort
  • Binary Search

When Sorting Lists or Arrays in computing, speed is key. So computer scientists devised many different types of sorting algorithms, each with their own speed (usually depicted with an O). You don't need to know what's called Big O Notation yet (mainly because its maths) but keep the symbol in mind when continuing.


Lets start with Bubble Sort, In my opinion the easiest to understand. Bubble sort sorts algorithms by comparing the 2 adjacent values in the array, swapping them if the 1st is bigger than the 2nd they're swapped. You'll need to know how to write each algorithm in pseudocode so I'll provide both below

/* Pseudocode */
FOR i FROM length-2 TO 0 STEP -1 DO
FOR counter FROM 0 TO i DO
  IF list[counter] > list[counter+1] THEN
    SET temp TO list[counter+1]
    SET list[counter+1] TO list[counter]
    SET list[counter] TO temp
  END IF
END FOR
END FOR
                      
# Python
for i in range(len(arr)-1, 0, -1):
for j in range(i):
  if arr[j] > arr[j+1]:
    # This line is the same as the 3 pseudocode lines
    arr[j], arr[j+1] = arr[j+1], arr[j]
                      

Standard Algorithms Continued

Prior Knowledge: Intermediate Algorithms

The 2nd Standard Algorithm you must learn is Insertion Sort. This one is a little trickier to understand


Insertion sort holds a value to start (usually index 0) and compares it to every other value in the array/list. Then it finds an element bigger than itself it inserts itself just before it. Then it stores the next index value

/* Pseudocode */
FOR index = 1 TO length(list)-1 DO
SET currentValue TO list[index]  
SET position TO index

WHILE position > 0 AND list[position-1] > currentValue DO
  SET list[position] TO list[position-1]
  SET position TO position - 1
END WHILE
END FOR
                        
# Python 
for index in range(1, len(arr)):
currentValue = arr[index]
pos = index

while position > 0 and arr[pos-1] > currentValue:
  arr[pos] = arr[pos-1]
  pos -= 1

arr[pos] = currentValue
                        

Finally we have binary search, which requires a sorted list/array to function

Binary search splits an array into 2 separate pieces and searches each one, if it doesn't find it it, it checks the number being searched and splits the array which has the closest value to it. It keeps going until the number is found

/* Pseudocode */
SET found TO False 
SET start TO 0
SET end TO LENGTH(arr)-1
RECEIVE goal FROM (INTEGER) KEYBOARD

WHILE(start <= end) AND found == FALSE DO 
SET mid TO INTEGER((start+end)/2)

IF arr[mid] == goal THEN
  SET found TO True 
ELSE IF arr[mid] < goal THEN 
  SET start TO mid+1
ELSE
  SET end TO mid-1
END IF
END WHILE
                        
# Python
found = False 
start, end = (0, len(arr)-1)

while (start <= end) and found == False:
mid = (start+end)//2

if arr[mid] == goal: found = True
elif arr[mid] < goal: start = mid+1
else: end = mid-1
                        

Summary

To Summarise

  • Bubble Sort - Sorts By Comparing 2 value together and swapping if the 2nd is bigger
  • Insertion Sort - Sorts By comparing 1 value to all others and once its found a bigger value, inserts itself behind it
  • Binary Search - Searches a List/Array To find a value by splitting the list/array in 2 then traversing each, continuing to until a value is found

At least 1 of these algorithms will come up in the exam, so memorise all 3 to be safe. Usually questions ask you to fill in the blanks in an algorithm and then final question is usually you constructing one of the algorithms from scratch for more marks (in my exam it was 6 and the algorithm was insertion sort).


Evaluation? Didn't we just do that?

Prior Knowledge: Software Development Cycle

When constructing software, you need to be able to evaluate certain aspects to check if the program works as intended. These are listed below

  • Fitness for Purpose
  • Efficiency
  • Usability
  • Maintainability
  • Robustness

You may have seen some of these terms before in the intermediate section, some might not have. So let's do some quick bullet points to sum up each one


Fitness for Purpose

  • Fitness for Purpose Establishes whether or not your program meets all user and functional requirements in the specification
  • Any omissions from the specification should be listed in this section
  • An example:
    • Optional Requirements
    • Any requirement that's met but there's perhaps an issue with

Maintainability

  • Perfective Maintenance - Happens in response to user requests for new features or to streamline code, should be identifiable in testing
  • Corrective Maintenance - Happens in response to discovering errors in the software, possibly from user reports, this should flag up in testing
  • Adaptive Maintenance - Happens in response to switching platforms or os versions, i.e adapting a windows 7 program to run in windows 10

Usability - As part of the design and testing you should conduct usability testing, its used to check how easy it is to navigate and use your program, for example: how intuitive your UI is in a mobile application.

DATABASES

Contents
  - WIP
  - WIP