FIT2082 (2019)

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Heaps - linked node

A heap can be made from a linked node, but thanks to completeness it can be implemented as an array For a node at k+1: ● Parent's parent: k//2 ● Parent = k ● Child left = 2*k ● Child right = 2*k+1

Recursive sorts merge sort

Merge sort is O(n log(n)) Merge sort halves the list, and once it's reached two elements, it sorts them and continues sorting as it combines the list.

Tranversing Binary Trees - methods

Methods ○ Preorder: root, then left, then right ○ Inorder: left, root, right ○ Postorder: left, right, root

Classess - Methods define

Methods define operations that can be performed by any object created as an instance of a class

Iterative sorting algorithms selection sort - complexity and why

O(n 2 ) Not stable

Iterative sorting algorithms bubble sort - complexity and why

O(n2) - ## incremental max number of swaps needed is n-1

Classes - Objects define

Objects are blocks of memory containing data and methods. In Python, every value is an object, they have both data and methods. We access the data and methods of an object in Python with dot notation. object.method()

Open addressing define

Open addressing ○ Each array position contains a single item ○ Upon collision, use an empty space to store the item ○ Requires array at least double the size as the number of element

Seperate chaining

Separate Chaining ■ Instead of looking for the next empty space, use a linked list to store collisions at the same hash location

MIPS instructions -Comparison Instructions Set less than

Set less than ■ slt $t0, $t1, $t2 ● if $t1 < $t2 then $t0 = 1 ● else $t0 = 0

MIPS instructions -Comparison Instructions Set less than immediate

Set less than immediate ■ slti $t0, $t1, x ● if $t1 < x then $t0 = 1 ● else $t0 = 0

3 parts of a loop MIPS

So a loop is composed of three parts: A condition that skips to the end of the loop when not true, and changes a variable if it's a for loop A set of instructions to be executed inside the loop A jump back to the loop condition

Recursion

Solving a large problem by reducing it to one or more subproblems that are the same kind as the original problem but simpler. Each subproblem is broken down until it's so simple it can be solved with a base case.

Queues immplemented with linked lists append

def append(self, item): new_node = Node(item, None) if self.is_empty(): self.front = new_node else: self.rear.link = new_node self.rear = new_node

Queues immplemented with linked lists is empty

def is_empty(self): return self.front is None

Linked list implementation is empty

def is_empty(self): return self.top is None

Stacks implemented with Linked list is empty

def is_empty(self): return self.top is None

Circular queue is empty

def is_empty(self): return self.count == 0

Queues implemented with arrays is empty

def is_empty(self): return self.rear == self.front

stack implemented with Arrays is empty

def is_empty(self): return self.top == 0

Stacks implemented with Linked list is full

def is_full(self): return False

Linked list implementation is full

def is_full(self): return False

Queues immplemented with linked lists is full

def is_full(self): return False

Queues implemented with arrays is full

def is_full(self): return rear == len(self.the_array)

Circular queue is full

def is_full(self): return self.count == len(the_array)

stack implemented with Arrays is full

def is_full(self): return top >= len(self.the_array)

Queues implemented with arrays peek

def peek(self): if self.is_empty(): raise Exception("Queue is empty") return self.the_array[self.front]

stack implemented with Arrays peek

def peek(self): if self.is_empty(): raise Exception("Stack is empty") return self.the_array[top - 1]

Stacks implemented with Linked list peek

def peek(self): if self.is_empty(): raise Exception("Stack is empty") return self.top.item

Queues immplemented with linked lists peek

def peek(self): if self.is_empty(): raise Exception("Stack is empty") return self.front.item

Stacks implemented with Linked list pop

def pop(self): if self.is_empty(): raise Exception("Stack is empty") item = self.top.item self.top = self.top.link return item

stack implemented with Arrays pop

def pop(self): if self.is_empty(): raise Exception("Stack is empty") self.top -= 1 item = self.the_array[top] return item

Stacks implemented with Linked list push

def push(self, item): self.top = Node(item, self.top)

stack implemented with Arrays push

def push(self, item): if self.is_full(): raise Exception("Stack is full") self.the_array = item self.top += 1

Linked list implementation reset

def reset(self): self.top = None

Queues implemented with arrays reset

def reset(self): self.front = 0 self.rear = 0

Queues immplemented with linked lists reset

def reset(self): self.front = None Self.rear = None self.count = 0

stack implemented with Arrays reset

def reset(self): self.top = 0

Stacks implemented with Linked list reset

def reset(self): self.top = None self.count = 0

Queues immplemented with linked lists serve

def serve(self): if self.is_empty(): raise Exception("Queue is empty") item = self.front.item self.front = self.front.link if self.front is None: self.rear = None return item

Circular queue serve

def serve(self): if self.is_empty(): raise Exception("The queue is empty") self.the_array[self.front] = item self.front = (self.front + 1) % len(self.the_array) self.count += 1 return item

Queues implemented with arrays serve

def serve(self): if self.is_empty(): raise Exception("Queue is empty") item = self.the_array[self.front] self.front += 1 return item

Circular queue size

def size(self): return self.count

Queues implemented with arrays size

def size(self): return self.rear - self.front

Recursive sorts general strategy

def sort(list): if base case: solve else [half1, half2] = split(list) sort(part1) sort(part2) combine(part1, part2)

Text segment

executable code goes here

Data segment

first - stores static data - its size is known before exectution and includes - class data, static variables, literal strings in the source coude, global variables second - dynamic ( heaps) objects and instance variables,. Grows 'downwards'

Linked List Implementation big picture

from node import Node

Stack segment

grows upwards/ towards heap § Contains the system stack § It is used for the temporary storage of: - Method information: • Local variables • Value of parameter • Return address - Saved register values (not studied in this unit)

Heaps

A heap is a binary tree with two special properties: ● Complete ○ Every level is full except the last ○ The last level is filled from the left ● Heap Ordered ○ Each child is smaller than or equal to its parents

Classes - Methods how does it differ to a function

A method is like a function except: ● It appears inside a class ● Its first arguments must be a reference to the instance whose method was called ○ The argument is named self ○ You must explicitly add self ○ Automatically added in call

Tree - inner Node

A node wih parents and children

Tree - Parent Node

A node with children

Tree - leaf node

A node with no children

Tree - Child Node

A node with parents

Tree - Subtree

A part of a tree

System Stack in MIPS - end of a funnction

Deallocate variables by popping allocated space from the stack

Tree - Width

the number od nodes in the level with the most nodes

start of MIPS function

# function entry addi $sp,$sp,-8 sw $ra,4($sp) sw $fp,0($sp) addi $fp,$sp,0 # copy $sp to $fp # 5*4 bytes=20. # 5 local variables ( n, a, i, item, item to right ) addi $sp, $sp,-20

item=the_list[item]

# item=the_list[i+1] # retrieving element i lw $t4, 8($fp) #storing address of memory allocated to $v0 lw $t0, -12($fp) #load i addi $t0,$t0,1 # i+1 addi $t1,$0,4 mult $t0,$t1 #4*(i+1) mflo $t2 add $v0,$t4,$t2 # the_list address +4*(i+1) lw $t3,4($v0) #load item i into to $t3 sw $t3, -20($fp) #item_to_right defined

exit MIPS function

# reinstating original frame pointer and return address lw $fp,0($sp) lw $ra,4($sp) addi $sp,$sp,8 # deallocating the stack bytes used for the storage ra and fp' jr $ra #returning to caller as well.

Trees define

######

Special Purpose Registers List

.HI and LO IR - instruction register PC - program counter

MIPS function entry from assignment

Saving sp to ra copying sp to fp then creating space for local variables

Iterative sorting algorithms Insertion sort

1. Main part: a. Split the list into two ■ A sorted part, starting with one element ■ An unsorted part, with the rest of the elements b. Extend the sorted part by taking any element in the unsorted section and inserting it into the sorted part, maintaining order 2. For every element in the unsorted list a. Store the first unsorted value, x, in a temporary place b. Shift all sorted elements larger than x one position to the right c. Copy x into the newly freed space

Super Linear Big O explain

Superlinear: O(n log n) Problem is broken up into sub-problems

Iterative sorting algorithms selection sort

1. Start at the leftmost unsorted element 2. Find the smallest element to the right 3. Swap it with the leftmost unsorted element

MIPS main components

32 General purpose registes - fast, expensive meory, physically inn CPU and each 32 bits size ALU - Arithmetic logic Unit - does the computatioons on register values Special registers - PC (Program Counter) - HI, LO (multiplication/division results) - IR (Instruction Register) - MAR/MRR/MWR (Memory Address/Read/Write Register),

Queues implemented with arrays overview

:)

Binary Search tree

A binary tree such that ● Every node has a key ● All keys in the left subtree of a node are less than the key of the node ● All keys in the right subtree of a node are larger than the key of the node ● All keys are unique

Circular queue define

A circular queue allows it to loop around when the rear reaches the end of the array, however this means that we can't tell when the queue is full or empty so we can use a counter or a reserved spot before the front to resolve this

Graph define

A graph is composed of ● A set of vertices, or nodes ● A set of edges A connected graph is one which every node is connected, there are no unreachable nodes. An acyclic graph has no cycles A tree is a connected acyclic graph

Python names and namespaces scope

A scope is the block of text where a namespace is directly accessible. That is, where there's no need to qualify a name. The scope is determined statically but is used dynamically ● Statically: so that you can always determine the scope of any name by looking at the program ● Dynamically: at runtime Python searches for names

Binary Tree define

A tree where each node has at most two children. A binary tree is height balanced if, for every node, the difference between the height of the left subtree and the right subtree is at most one. A perfect binary tree is one which all parents have two children and all leaves are at the same level.

Python - Variable representation

A variable is a name that identifies something. The name usually refers to a memory location. Like in MIPS, memory is divided into portions, and each portion has an address. In Python, the variable is a reference to a memory location containing ● The data ● The type of date ● Metadata

Python - creating variables

A variable is created when you first assign it a value x = value The actual value of x is the address to the data, Python doesn't require a specified type When a value is changed it only alters the reference

MIPS Memory Diagrams

A way of representing memory allocated to variables, including their ● Addresses ● Contents ● Variable Names This isn't crucial for global variables in the data segment. Every variable has a label to identify it, this label is used to access global variables. Local variables don't have a label because it should only be accessible to the function or method running it as a variable may have the same name within different scopes A memory diagram following the stack format: 0x6FFFFFF4 var 10 0x6FFFFFF8 old $fp 0x70000020 0x6FFFFFFC $ra 0x00401000 0x70000000 arg 14 0x... ? ?

List ADT Adding and deleting elements example

Adding elements: add an item at the position at length, then increment length Removing elements: decrement length.

MIPS Instructions - Arithmetic Addition

Addition ■ add $t0, $t1, $t2 ■ $t0 = $t1 + $t2

MIPS Instructions - Arithmetic Addition immediate

Addition immediate ■ addi $t0, $t1, x ■ $t1 = $t1 + x

Advantages of recursion

Advantages ● More natural ● Easier to prove correct ● Easier to analyse

Advantages of ADT

Advantages of ADT ● Simplicity ● Maintenance ● Flexibility and Reusability ● Portability

list comprehension

Allows you to easily get lists and iterators based on functions and conditions Python rules for creating lists intelligently s = [x for x in range(1:51) if x%2 == 0] [2, 4, 6, 8, 10, 12, 14, 16, etc]

Abstract Data Types traits

An abstract data type: ● Provides information regarding ○ The possible values of the type and their meaning ○ The operations that can be done on them ● Users interact with the data only through provided operations

Linked Data structures Advantage

Advantages: ● Fast deletion and adding of intermediate elements ● Resizable ● Less memory than a relatively empty array

Overload operators

All classes are derived from the built-in object, Object. This defined methods like __str__ and __int__. Your class inherits the definition, but you can also redefine it.

Recursion vs Iteration requirements for recusive implementation

Any iterative function can be implemented by recursion. ● Iterators are replaced by function calls ● The base case is the related condition of the loop ● Needs an auxiliary function to prepare conversion

Recursion vs Iteration requirements for iteratiev implementation

Any recursive function can also be implemented using iteration ● Need to store past results

Binary search tree - about search insert and delete

Binary trees are good for searching, inserting, and deleting ● Searching is binary ● Modifying links are constant ○ Deleting ■ Find the node and if ● A leaf: set to none ● A node with one child: parent reference is set to child ● A node with two children: Parents reference is set to the node's successor ○ The leftmost node with no left nodes ● Can be traversed in particular orders

MIPS instructions -Conditional Branch Instructions Branch if equal

Branch if equal ■ beq $t0, $t1, address

System Stack in MIPS - Beginning of a function

At the beginning of a function ● Allocated variables by pushing space onto the stack ● Initialize space by storing values in newly allocated space

Recursive sorts quick sort

Best: O(n log(n)) Worst O(n 2 ) ● The split: partition the list into two ○ One with elements smaller than the pivot ○ Another with elements greater than p ● The combination: append with the pivot in the middle

Better heap construction

Better Heap Construction If we know many elements in advance we can do it more quickly. Each balanced subtree in a heap is a heap, so we can build it up from the bottom by making little trees, heapifying them, then joining them, then heapifying, etc.

MIPS instructions -Conditional Branch Instructions Branch if not equal

Branch if not equal ■ bne $t1, $t2, address

Iterative sorting algorithms bubble sort

Bubble Sort 1. Start with the leftmost element 2. Compare the left element, x, to its neighbour on the right, y 3. If x>y, swap 4. Consider the next position to the right

0x10000000 - 0x7FFFFFFF

Data segment heap stack segment ( temp storage)

Classess define and define attributes

Classes A class is a blueprint for objects. That is, a class defines its attributes: ● The data stored by the object ● The methods that can be used by the object ● How its initialised Classes use the following syntax class ClassName: def methodName(arguments): code Every object is created by instantiating a class

classes python

Classes are objects within python that can be instantiated with their own data and methods. Every method within a class has a reference to itself

Cluster define

Cluster ■ A sequence of full hash table slots which grow larger as items are added

Conflict resolution define

Conflict occurs when a hash function produces the same output for two separate inputs. There are two main approaches to resolving these conflicts: - seperate chaininng and open addressing

Constant big O explain

Constant: O(1) Running time doesn't depend on n

when to use arrays

Contiguous Storage if: ● Known number of elements ● Few insertions or deletions needed ● Lots of searches on a sorted list ● Access to elements based on their position

MIPS Assembly directories

Directories always start with a dot. These don't assemble to machine language, they're used to allocated space and data. ● .data ○ Tells assembler it's working in the parts of the program to create things in the data segment ● .text ○ Tells the assembler to work in the text segment ● .space N ○ Creates N bytes of empty space ● .word W1[, W2, W3, ...] ○ Allocate 4 byte words and store the WN values in them ● .asciiz "string" ○ Allocates a sequence of 4 byte values and a zero byte to represent a string

Disadvantages of recusion

Disadvantages ● Runtime overhead ● Memory overhead

Linked Data Structure disadvantage

Disadvantages: ● More memory when relatively full ● Operations are time-consuming (no random access

MIPS Instructions - Arithmetic Division

Division ■ div $t1, $t2 ■ LO = $t1//$t2, HI = remainder

Double hashing define

Double Hashing ■ Whenever a collision occurs a secondary hash function is used to determine the step size. Eliminates the effect of clusters

System Stack in MIPS - during a function

During a function ● Push and pop variables using lw and sw

Priority Queue

Each element has a priority, we process the higher priorities first. There are two main operations ● add(element) ● get_next() For implementation, we use the usual built-in methods and the two new ones. It can be implemented with Array lists, linked lists, or a binary search tree

Exponential Big O explain

Exponential: O(2n) Combinatorial explosion

Factorial Big O explain

Factorial: O(n!) Finding all permutations of n items

Functions python

Functions are a portion of code which can be called to from anywhere in the same namespace

MIPS Function

Functions are used to encapsulate code, allow abstractions, and hide information. For function calling in MIPS we use the jal command, which is like a jump but it saves the address after where it was called from into $ra. The jr command can then be used to jump to the address that was stored in $ra.

Time complexity Big O notation

Instead of using exact running time equations we can use approximations, using the upper bound. It gives us a way of describing the growth rates of a methods running time with its input size.

Hash function properties

Hash function properties ● Type-dependent ● Return value in array range ● As fast as possible ● Minimise collisions

Hash Tables define

Hash tables aim to achieve O(1) as the best case for inserting, searching and deleting as much as possible. This is achieved with arrays, but each item needs a key

Python - assigning variables to other variables

If we set a variable to another, we're actually giving the two variables the same reference. If we now change the value of one variable its reference is retained while the other variables reference is preserved

Names and Namespaces

In Python, all identifiers are names. Namespaces are a mapping of names to objects, like a dictionary; each file, or module has its own namespace. So two classes and functions with the same name should not be placed in the same file, class, or function, else one will overwrite the other. Functions have their own namespace while being run too, Python creates a local namespace which is deleted when the function is completed. A name is bound in many ways in Python. If any of these are inside a function it makes the name local to the function

Binary Tree Complexity

In terms of complexity, the height is O(log n) for a balanced tree and O(n) for unbalanced

Algorithm Classifications Incremental Algorithms

Incremental algorithms don't need to recompile everything after a small change. If we need to add an element into a sorted list, bubble will be incremental when inserted into the front; it only needs to iterate once

define invariant

Invariant: property that remains unchanged - At a particular point, or throughout an algorithm, or ... In bubble sort there are many invariants: - Example: after every traversal, the list has the same elements - Also: in each traversal at most n-1 swaps are performed, where n is the length of the list

__init__ method

It is the first method in a class and is called

Stack Operations follows as

Its operations are as follows ● Create a stack (stack) ● Add item to top (Push) ● Take item off top (Pop) ● Look at item on top (Peek) ● Is the stack empty ● Is the stack full ● Empty the stack

Queues operations as follows

Its operations are as follows: ● Create the queue (Queue) ● Add item to back (Append) ● Take item off the front (Serve) ● Is the queue empty ● Is the queue full

MIPS instructions -Control transfer instructions Jump and link to label

Jump and link to label ■ jal label

MIPS instructions -Control transfer instructions Jump and link to register

Jump and link to register ■ jalr $t0

MIPS instructions -Control transfer instructions Jump to address in register

Jump to address in register ■ jr $t0

MIPS instructions -Control transfer instructions Jump to label

Jump to label ■ j label

types of open addressing

Linear probing quadratic probinng doube hasing seperate chainning cluster 5 types

Linear big O explain

Linear: O(n) Each element requires a fixed amount of processing

Linked Data structures define

Linked data structures are a connection of nodes, each node contains a data item and a link to another node

When to use linked list

Linked storage if: ● Unknown list size ● Many insertions and deletions are needed ● Most operations need traversal of the list from the first element

Python - lists

Lists in Python are implemented as arrays but are also objects. A variable is set as a reference to a list, and each item in the list is a reference to an object. Python lists are mutable, the value of each item in the list can actually change (just the reference value, not the value being referenced), almost all other objects are considered immutable, in that only the references can be altered.

MIPS instructions - Load and store Load word

Load word ■ lw $t0, address ■ $t0 = contents(address)

Logarithmic big O explain

Logarithmic: O(log n) Problem is broken up into smaller problems *

MIPS Input/ output

MIPS does Input/Output by asking the OS with the syscall command. To do this: 1. Work out the service required 2. Put the call code in $v0 3. Put arguments in $a0 and $a1 4. Perform syscall 5. Results are stored in $v0

Algorithm Classifications Stable algorithm

Maintains the relative order among elements. Sorting algorithms which can swap elements more than one space may cause a change in order if it swaps over an element with the same key

MIPS allocating space in the heap

Make a syscall with the code 9. In $a0 set it as the number of bytes to allocate in the heap. The address for the start of the heap is kept in $v0

List ADT adding and deleting elements explanation

Most implementations of lists use arrays, however, arrays have a fixed size, so, lists implemented need two things ● An array with a big size ● A count of the number of elements in the array Ab empty list has a length of zero, however, the array would still be large. To implement lists in Python we create a Python list with two elements; the length of the list and an array of fixed size

MIPS instructions - Data Movements Move from Hi

Move from hi ■ mfhi $t0 ■ $t0 = HI

MIPS instructions - Data Movements Move from Lo

Move from lo ■ mflo $t0 ■ $t0 = LO

MIPS Instructions - Arithmetic multiplication

Multiplication ■ mult $t1, $t2 ■ LO = $t1 * $t2, HI = overflow

HI and LO register

Multiplying two 32 bit numbers may require 64 bits to fit the result ○ HI contains the overflow, the large 32 bits ○ LO contains the rest, the small 32 bits Integer division may result in a remainder, after integer division ○ LO is the integer result of the division ○ HI is the remainder of the division

Pqueue Sort

PQueue Sort Using get_next from a priority queue can be used to sort lists quickly 1. Put elements in p-queue 2. Call get_max n times

Python names and namespaces how it searches

Python searches for names as follows 1. In the innermost scope 2. In the scope of enclosing functions 3. In the modules global names 4. In the namespace of in-built names

Quadratic probing

Quadratic Probing ■ Rather than searching linearly, check every step squared until an empty slot is found. This reduces the likelihood of clustering

Quadratic big O explain

Quadratic: O(N2) Processes pairs of data items

Queues implemented with how many elements

Queues are implemented with three elements: ● An array to store the items ● A pointer to the front ● A pointer to the rear

Queues define

Queues are lists that follow first in, first out (FIFO) access. Access to other elements in the list is unnecessary and forbidden

Recusion functions must have

Recursion functions must have ● At least one base case ● At least one recursive call whose result is combined ● Convergence towards the base case

MIPS recursion

Recursive functions end up calling themselves to solve a simpler version of the same problem. Functions calling themselves work the same way as normal function calling; each invocation has its own stack frame ( pretty sure we dont need to know this)

Recursive sorts

Recursive sorts are achieved with divide and conquer algorithms, they split the problem into subproblems. Such algorithms run at higher efficiency.

RISC vs CISC

Reduced Instruction Set Computer All instructions are • Same length (4 bytes, that is, 32 bits - a "word" for us) • Of similar complexity (simple) • (Mostly) able to run in same time (1 clock cycle) • Easily decoded and executed by computer hardware - Advantages: easier to build, cheaper, consumes less power Intel x86 is considered CISC ( Complex instruction set computer) - Instructions vary in length, complexity and execution time - Decoding and running instructions requires hardware-embedded program (microcode) - Advantage: potential for optimisation of complex instructions

Abstract Data Types define/ what do they determine

Refers to a classification that determines: ● The possible values for that type ● The meaning of those values ● The operations that can be done on them ● The way the values are implemented

General Purpose Registers (GPRs)

Registers in assembly are given a "$" prefix to identify them and range from $0 to $31, giving us 32 registers

0x00000000 - 0x003FFFFF

Reserved for OS

0x80000000 - 0xFFFFFFFF

Rserved for OS

MIPS functions - passing data **

Some functions have parameters and some return values. We can use reserved registers to achieve this (●** Use $a0 - $a3 for parameters) ● Use $v0 and $v1 for returns This has its limits, however, as we there may not be enough registers to achieve a functions requirements. Important register values also need to be recorded, since $ra and $fp are going to change, therefore they are stored in the stack upon entry. Upon return, the stack pointer is set to the frame pointer and the old $ra and $fp values are restored.

Stacks are implemented with how many elements

Stacks are implemented with two elements: ● An array to store items ● An integer indicating the top

Stacks define

Stacks are lists that follow the last in, first out (LIFO) access. Access to other elements in the list is unnecessary and forbidden

MIPS instructions - Load and store Store word

Store word ■ sw $t0, address ■ contents(address) = $t0

MIPS Instructions - Arithmetic substraction

Subtraction ■ sub $t0, $t1, $t2 ■ $t0 = $t1 - $t2

0x00400000 - 0x0FFFFFFF

Text segment

System Stack in MIPS - $fp

The $fp register indicates the bottom of the stack. This is useful for returning to old stack pointers, but also, it's easier to access variables with the frame pointer as it gives us a frame of reference from the beginning of the stack, which remains unchanged throughout a function

System Stack in MIPS - $sp

The $sp register indicates the top of the stack, its value changes during the execution of a function. To push elements to the stack you need to subtract the stack pointer by four, allocating 32 bits, then to pop you add four to the stack pointer.

Tree - Root Node

The Node with no parents

Getting data out of main memory

The address to be loaded from goes into the MAR - The memory controller gets told to do a read - The data at that address goes into the MRR - The MRR is copied to the destination register (GPR) specified in the instruction

Tree - nodes

The connections between each branch

Tree - edges

The connections between each node

Put data in main memory

The contents of the GPR specified in the instruction are copied to the MWR - The address to be stored to goes into the MAR - The memory controller gets told to do a write - The data in the MWR gets written to memory

MIPS Accessing main memory

The data lives in the main memory, so we have to load data to a register then back to memory once done Each segment has its own context for the data being used To get data out of memory we use a load instruction and a store instruction to put it back.

Tree - Levels

The different sectiosn where the branches reside

IR (Instruction Register)

The instructions register stores the instruction currently being executed. The first 6 bits are operation code, the code referring to the instruction. The opcode tells the control circuit which microinstructions need to be followed the rest of the bits are operands are the input output values? Where machine code/instructions are held for decoding and execution

Tree - depth

The level of a node

List ADT - what makes it a list

The list ADT is used to store items, what makes it a list is: ● Elements have an order ● Must have access to the first item ● From one position you can always access the next For our own definition of a list, we will use arrays to implement is

PC (Program Counter)

The program counters tell the computer where it's up to in the code. It holds the memory address of the code being executed. Jump writes a new value to the PC to move the execution to a new place in the program. Branch instructions do this if a condition is met.

Python Exceptions

There are two main situations where we need to deal with errors: ● When reading an input ● When a precondition isn't met If an error is detected we usually print an error message. Modern languages use exception handling.

Exception handling code example with explanation

This function will first execute the try clause. If there's no exception, skip the except clause. If there is an exception, skip to the except clause and: ● If the type matches the exception: ○ Execute except clause ○ Continues execution after the try statement ● If it doesn't match: ○ Control is passed to outer try statements ○ If no handler is found, it is an unhandled exception

MIPS Arrays - calc the address of a[n]

To compute the address of a[n] ● Determine the start address ○ Address in a + 4 ○ The numerically smallest address ● Determine the size of an element in a ○ In bytes (usually 4 bytes) ● Compute n address ○ n = start + (size * k)

Heaps to get max item

To get the max item, just select the item at the top of the tree, swap it with the list item in the list and take out the max. Now move the top item down until it's equal to or larger than its children.

Heaps - to insert

To insert an item into a heap you place is at the next space in the tree and then, if the parent is larger, then swap the item and parent until the heap is valid.

Iterators

To traverse a list from outside the class we would have to access the implementation. We need a way of creating an iterator object to start the iterations. ● An object other than the list because ○ It needs to change ○ We might need several iterations ● In Python iterators are returned with __iter__ This means we need an iterator class to create the objects, with this class needing a way to return the next element. We need to create an iterator class for the list

Iterators vs iterables

We have made out List class iterable because it defines __iter__ The iterator object we created, ListIterator, defines __iter__ and __next__. So now we can use for loops to iterate over iterables and iterators. Iterators can also be given methods like any other class.

MIPS Labels and Symbols

We use labels to name memory location in the data or text segment. The assembler uses a symbol table when it sees a label being defined and puts the label and address location into the table. When a label is used it looks the name up in the table to find its address

MIPS Arrays

When translating from lists in Python we assume ● They have a fixed length ● Only have integers ● Initialise as zero ● The data for a list is only ○ It's length ○ It's elements

MIPS Iteration

While tests whether a condition is met before loop entry For is a shorthand for while where it runs depending on the state of a temporary variable

Big O notatioon - Best/worst cases

Worst cases give us a guarantee for all inputs. Best case is correct for at least one condition of the input. When time complexity is unspecified we consider it to be worst case.

Iterative sorting algorithms Insertion sort - complexity and why

Worst: O(n 2 ) Best: O(n) Stable and incremental when added to the back

Tree - Path

a collection of connected branches

what is a word

chunk of bits ( 8.16.32 or 64) we will use 32 bits = 4 BYTES

Linked Data Structure Class Node

class Node: def __init__(self, item=None, link=None): self.item = item self.next = link

Circular queue append

def append(self, item): if self.is_empty(): raise Exception("The queue is full") self.the_array[self.rear] = item self.rear = (self.rear + 1) % len(self.the_array) self.count += 1

Queues implemented with arrays append

def append(self, item): if self.is_full(): raise Exception("Queue is full") self.the_array[self.rear] = item self.rear += 1

List ADT example - get item, length, lin_search

def List(size): return [None]*size def get_item(the_list, index): return the_list[index] def length(the_list): return len(the_list) def lin_search(the_list, item): for index in range(len(the_list)): if item == the_list[item]: return True return False

Linked list implementation __getitem__

def __getitem__(self, i): current = self.top while i > 0: if current.link is None: return False current = current.link i -= 1 return current.item

Linked list implementation initialise

def __init__(self, _=None): self.top = None

Stacks implemented with Linked list __init__

def __init__(self, _=None): self.top = None count = 0

Queues immplemented with linked lists init

def __init__(self, _=None): self.front = None self.rear = None count = 0

Circular queue init

def __init__(self, size): ... ### self.count = 0

Queues implemented with arrays __init__

def __init__(self, size): self.the_array = [None] * size self.front = 0 self.rear = 0

stack implemented with Arrays __init__

def __init__(self, size): self.the_array = [None] * size self.top = 0

Stacks implemented with Linked list __len__

def __len__(self): return self.count

Queues immplemented with linked lists len

def __len__(self): return self.count

stack implemented with Arrays _len_

def __len__(self): return self.top

Linked list implementation __len__

def __len__(self): size = 0 current = self.top while current is not None: size += 1 current = current.link

Linked list implementation __setitem__

def __setitem__(self, i, item): current = self.top while i > 0: if current.link is None: return False current = current.link i -= 1 Current.item = item

Hash function

key ⟶ hash function ⟶ pos ⟶ array[pos]

Why assembly language needed

machine code hard to write Supports comments, variable names, line labels, etc - Has human -readable versions of machine instructions - But is easily converted to machine language • Usually a 1-to-1 relationship between each assembler language instruction and its equivalent machine language instruction

Machine Code

not in Java or Python but in machine language machine code is stores in memory as bit patterns

MIPS control transfer statement

replace the PC value with the address value of the speciifc destination

Tree - Height

the highest level in the tree

Exception handling define 3 parts

● Exception ○ Runtime event that breaks the normal flow of execution ● Exception Handler ○ Block of code that can recover from the event ● Exception Handling ○ Mechanism to transfer control to a handler

MIPS Properties of local variables

● Must be created upon entry ● Must be destroyed on exit ● Other functions can be called between with the same rules So the structure is like a stack; LIFO.

seperate chaining define

● Separate Chaining ○ Each array position contains a linked list of items ○ Upon collision, the cloned element is added to the lis

Recursive notation

● Unary: A single recursive call ● Binary: Two recursive calls ● N-ary: n recursive calls

MIPS instruction execution

●Fetch next instruction from memory ● Decode instruction in the IR to determine type ● Execute instruction, then go to the next instruction

Big O table

▪ If run time depends only on input size: best = worst

Linear probing define

○ Linear Probing ■ When a collision occurs commit a linear search from the key's location until an empty slot is found

MIPS instructions -Shifting Shift left logical

○ Shift left logical ■ sll $t0, $t1, x ■ $t0 = $t1 * 2 x

MIPS instructions -Shifting Shift right arithmetic

○ Shift right arithmetic ■ sra $t0, $t1, x ■ $t0 = $t1/2 x

Hash Tables 3 aspects

● Data ○ Item to be stored ○ The items unique key ● Structure: ○ Large array ● Operations ○ Hash function ■ Maps key to position ○ Insert ○ Search ○ Delete

Direct vs indirect recursion

● Direct: recursive calls are calls to the same function ● Indirect: recursion through two or more methods


Ensembles d'études connexes

English II: Twelve Angry Men Test Review

View Set

Wordpress Multiple Choice Questions Practice

View Set

3.08 Testing Tips - Understanding Complexity

View Set

Chapter 1,2,3,4,5 and 7 Linux/UNIX

View Set

Science What Changes Occur from Infancy to Adulthood?

View Set

Информатика ЕНТ подготовка 2023

View Set

Adaptive Quiz Nursing Care of the Newborn

View Set