Consider this array:
int[] numbers = { 0, 1, 1, 2, 3, 5, 8 };
When you ask for numbers[3]
, internally the computer does this fake pseudo-code:
func array_access(index) {
address = numbers; // numbers is actually an address!
shifted_address = address + index * size_of_integer;
return value_at_memory_location(shifted_address)
}
add
or push
to add new things to the endremove
to remove an item at a particular index
L = ['a', 'b', 'c']
L.append('d') # add onto the end
L.extend(['e', 'f', 'g']) # add multiple items
L.insert(1, 'sneaky') # insert 'sneaky' at index 1
L.pop(1) # remove the item at index 1
L.pop() # remove the item at the end
pop()
and append
pop(0)
and append
Given two sets S and T
S = set([1, 2, 3])
T = set([3, 4, 5])
S & T # Intersection, gives set([3])
S | T # Union, gives set([1, 2, 3, 4, 5])
S - T # Difference, gives set([1, 2])
2 in S # Boolean, is 2 in the set?
6 not in S # Boolean, is 6 not in the set
A = set(['a', 'b', ...])
B
A - B
''.join(sorted(A - B))
D = {} # empty dictionary declaration
D = { 'Georgia' : 'GA', 'Florida' : 'FL' } # declaring a dictionary with data
D['New York'] = 'NY' # adding a new entry
D['Georgia'] # Spits out 'GA'
'Alabama' in D # Is 'Alabama' a key?
D.keys() # provides an iterable over the dictionary's keys are
D.values() # provides an iterable over the dictionary's values
class Node:
def __init__(self, value):
# initially, this node has no parent, nor any children
self.value = value
self.parent = None
self.children = []
def add_child(self, child):
# to add a child, add the passed node to the list of children,
# but also link it back to "self", which is the parent
child.parent = self
self.children.append(child)
def traverse(root, do_something):
# This is the list of nodes we have yet to visit. We start with just
# the root
to_visit = [root]
# while there are more nodes to visit
while len(to_visit) is not 0:
# get the next node to visit.
# Note: to_visit.pop() gives a Depth-First-Search
# to_visit.pop(0) gives a Breadth-First-Search
# check out https://en.wikipedia.org/wiki/Tree_traversal
#next_node = to_visit.pop()
next_node = to_visit.pop(0)
# Add all of the children of this node as nodes to visit
to_visit.extend(next_node.children)
# do something with the node (we passed the "action" as a parameter)
do_something(next_node)
# Building a tree here
A = Node('A')
# First level
B = Node('B')
A.add_child(B)
C = Node('C')
A.add_child(C)
# Second level
D = Node('D')
B.add_child(D)
E = Node('E')
B.add_child(E)
F = Node('F')
C.add_child(F)
# Call the traverse function with a starting node, and a function to
# perform at each node
traverse(A, lambda node : print(node.value))