Deck 1 Flashcards

1
Q

Linear Structures

A

Data structure that is thought of having two ends, left and right or sometimes front and rear. Top and bottom. Distinguished by how data is added and removed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

stack

A

push-down stack. top to base linear data structure. LIFO. For example, every web browser has a Back button. As you navigate from web page to web page, those pages are placed on a stack (actually it is the URLs that are going on the stack).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Stack Code

A
class Stack:
  def \_\_init\_\_(self):
      self.stack = []
  def push(self, value):
      return self.stack.append(value)
  def pop(self):
      if self.is_empty():
          return None
      else:
          return self.stack.pop()
  def peak(self):
      if self.is_empty():
          return None 
      else:
          return self.stack[-1]
  def size(self):
      return len(self.stack)
  def is_empty(self):
      return self.size() == 0
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Queue Code

A
class Queue:
    def \_\_init\_\_(self):
        self.queue = []
    def enqueue(self, val): # critical differnce between stack and queue
        self.queue.insert(0,val)
    def dequeue(self):
        if self.is_empty():
            return None
        else:
            return self.queue.pop()
    def size(self):
        return len(self.dequeue)
    def is_empty(self):
        return self.size() == 0
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Binary Search Code

A
class BinarySearch(alist, val):
    if len(alist) == 0:
        return False 
    else:
        midpoint = len(alist)//2
        if val == alist[midpoint]:
            return True
        else:
            if val < alist[midpoint]:
                return BinarySearch(alist[:midpoint], val)
            else:
                return BinarySearch(alist[midpoint+1:], val)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Queue Data Structure

A

FIFO. front to rear. basically every line you can think of. Common function are insert(queue) or pop(dequeue)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Hash Table Get Function

A
def hashFunction(self, key, size):
        return key%size
    def rehash(self, oldhash, size):
        return (oldhash+1)%size 

def get(self, key):
startingslot = self.hashFunction(key, len(self.slots))
data = None
stop = False
found = False
position = startingslot
while self.slot[position] != None and not stop and not found:
if self.slot[position] == key:
found = True
data = self.data[position]
else:
position = self.rehash(position,len(self.slots))
if position == startslot:
stop = True
return data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Hash Table put function

A
def hashFunction(self, key, size):
        return key%size
def rehash(self, oldhash, size):
        return (oldhash+1)%size 
def put(self,key,data):
      hashvalue = self.hashfunction(key,len(self.slots))
  if self.slots[hashvalue] == None:
    self.slots[hashvalue] = key
    self.data[hashvalue] = data
  else:
    if self.slots[hashvalue] == key:
      self.data[hashvalue] = data  #replace
    else:
      nextslot = self.rehash(hashvalue,len(self.slots))
      while self.slots[nextslot] != None and \
                      self.slots[nextslot] != key:
        nextslot = self.rehash(nextslot,len(self.slots))

      if self.slots[nextslot] == None:
        self.slots[nextslot]=key
        self.data[nextslot]=data
      else:
        self.data[nextslot] = data #replace
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Deque

A

Deques are data structures that allow hybrid behavior like that of stacks and queues. Double-ended queue order collection. allow for LIFO and FIFO mixture of stack and queue
adding an removing from the front is O(1) whereas adding or removing from the end is O(n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Deque code

A
class Deque:
    def \_\_init\_\_(self):
        self.items = []
    def isEmpty(self):
        return self.items == []
    def addFront(self, item):
        self.items.append(item)
    def addRear(self, item):
        self.items.insert(0,item)
    def removeFront(self):
        return self.items.pop()
    def removeRear(self):
        return self.items.pop(0)
    def size(self):
        return len(self.items)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Linked List

A

Unordered list. The location of the next item is stored in the item so the relative position doesn’t matter. First item is know as the head. Basic building block is a node. Node will contain data and the next node reference. None indicates there is no next node.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Node function names

A

__init__, getData, getNext, setData, setNext

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Node Code

A
class Node:
    def \_\_init\_\_(self,initdata):
        self.data = initdata
        self.next = None
    def getData(self):
        return self.data
    def getNext(self):
        return self.next
    def setData(self,newdata):
        self.data = newdata
    def setNext(self,newnext):
        self.next = newnext
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

UnorderedList functions

A

__int__, isEmpty O(1), add O(n), size O(n), search O(n), remove O(n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

UnorderList Code

A
class Node:
    def \_\_init\_\_(self,initdata):
        self.data = initdata
        self.next = None
    def getData(self):
        return self.data
    def getNext(self):
        return self.next
    def setData(self,newdata):
        self.data = newdata
    def setNext(self,newnext):
        self.next = newnext

class UnorderedList:

    def \_\_init\_\_(self):
        self.head = None
    def isEmpty(self):
        return self.head == None
    def add(self,item):
        temp = Node(item)
        temp.setNext(self.head)
        self.head = temp
    def size(self):
        current = self.head
        count = 0
        while current != None:
            count = count + 1
            current = current.getNext()
    return count

def search(self,item):
    current = self.head
    found = False
    while current != None and not found:
        if current.getData() == item:
            found = True
        else:
            current = current.getNext()

    return found
    def remove(self,item):
        current = self.head
        previous = None
        found = False
        while not found:
            if current.getData() == item:
                found = True
            else:
                previous = current
                current = current.getNext()
    if previous == None:
        self.head = current.getNext()
    else:
        previous.setNext(current.getNext())

mylist = UnorderedList()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

ordered list add function

A
def add(self,item):
    current = self.head
    previous = None
    stop = False
    while current != None and not stop:
        if current.getData() > item:
            stop = True
        else:
            previous = current
            current = current.getNext()
    temp = Node(item)
    if previous == None:
        temp.setNext(self.head)
        self.head = temp
    else:
        temp.setNext(current)
        previous.setNext(temp)
17
Q

Stack Functions

A

The fundamental operations for a stack are push, pop, and isEmpty.

18
Q

Queue Functions

A

The fundamental operations for a queue are enqueue, dequeue, and isEmpty.

19
Q

Recursion

A

a method of solving a problem by breaking it down into smaller pieces. Usually calls itself.

20
Q

3 laws of recursion

A

A recursive algorithm must have a base case.
A recursive algorithm must change its state and move toward the base case.
A recursive algorithm must call itself, recursively.

21
Q

Sequential search

A

O(n) for ordered and unordered lists. Check each value along the way.

22
Q

binary Search

A

O(log n) half the list each time and go to the half the item belongs in

23
Q

hash table

A

constant time searching or O(1) the idea is that if you give me an item i can use the hash function to find its location in the hash table. Collison resolution aside

24
Q

remove punctuation and split words from string

A

[word.strip(string.punctuation) for word in data.split()]

25
Q

difference of two vectors code

A
def inner_product(d1, d2):
    sum = 0.0
    for word in d1:
        if word in d2:
            sum += d1[word]* d2[word]
    return sum
def angle_difference(d1, d2):
    numerator = inner_product(d1, d2)
    denominator = math.sqrt(inner_product(d1, d1)* inner_product(d2, d2))
    return math.acos(numerator/denominator)
26
Q

Count word occurrence from document code

A
def count_word(d):
    count = {}
    for word in d:
        if word in count:
            count[word]+=1
        else:
            count[word] = 1
    return count
27
Q

merge sort

code

A

O(n)

def merge_sort(alist):
    if len(alist)>1:
    half = len(alist) //2 # split the deck
    lefthalf =alist[:half]
    righthalf = alist[half:]
    print("halves", lefthalf, righthalf)
    left = merge_sort(lefthalf) # recursive call on the left side
    right = merge_sort(righthalf) # recursive call on the right side

    i=0
    j=0
    k=0
    while i < len(lefthalf) and j < len(righthalf): # while the indexes are less than the length
        if lefthalf[i] < righthalf[j]: # if left is less than right
            alist[k]=lefthalf[i] # add the left to the sorted list
            i=i+1
        else:
            alist[k]=righthalf[j]
            j=j+1
        k=k+1

    while i < len(lefthalf):
        alist[k]=lefthalf[i]
        i=i+1
        k=k+1
        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1
    print("Merging ",alist)

alist = [20,14,1,3,2,7,9,6,4]

x = merge_sort(alist)

28
Q

merge sort

A

divide the list down to prime left and prime right then reassemble the list based on which is bigger.
Recursive formula with O(n)

29
Q

implement an algorithim to test if a string is unique

A
def unique(string):
    # Assuming character set is ASCII (128 characters)
    if len(string) > 128:
        return False
    char_set = [False for _ in range(128)] # create False spots for possible characters
    for char in string: # character by character 
        val = ord(char) # get the positional value 
        if char_set[val]: # if you have already added that positional value it is not unique
            # Char already found in string
            return False
        char_set[val] = True # otherwise add it
return True # if you make it through the list it is unique
30
Q

Heap code

A
class BinHeap:
    def \_\_init\_\_(self):
        self.heapList=[0] # intialize a list at 0
        self.currentSize = 0 # size at zero
'''
given i i//2 is the left child, i//2+1 is the right child
'''
def minChild(self,i):# so given a node return its smaller child
    if i*2+1> self.currentSize: #if there is no right child just return the left
        return i*2 # return the node
    else:
        if self.heapList[i*2]< self.heapList[i*2+1]: # if the child to the right is smaller return it
            return i*2
        else:
            return i*2+1 #otherwsie give me the left child
    def percDown(self, i):
        while (i*2)<= self.currentSize: # while staying on the current level
            mc = self.minChild(i) # find the lowest child
            print("Checking", self.heapList[i], self.heapList[mc])
            if self.heapList[i] > self.heapList[mc]:
                print("It was bigger flipping", self.heapList[i], self.heapList[mc])
                tmp = self.heapList[i]
                self.heapList[i] = self.heapList[mc]
                self.heapList[mc] = tmp
            i= mc
def buildHeap(self, alist):
    i = len(alist) // 2 # start at n/2
    self.currentSize = len(alist) # Looking at the whole tree
    self.heapList = [0]+alist[:] # combined the heap list with the list
    while(i > 0):
        self.percDown(i)# swap nodes to achieve max heap
        i -=1
    def sort(self):
        result = []
        while self.currentSize >= 1:
            retval = self.heapList[1]
            self.heapList[1] = self.heapList[self.currentSize]
            self.currentSize =  self.currentSize -1
            self.heapList.pop()
            self.percDown(1)
            result.append(retval)
        return result
    def \_\_str\_\_(self):
        return str(self.heapList)