Algorithm Examples Flashcards

1
Q

Fibonacci - Python

A
def fib(n):
    """
    >>> [fib(n) for n in range(10)]
    [0, 1, 1,  2, 3, 5, 8, 13, 21, 34]
    """
    if n <= 1:
        return n 
    return fib(n-1) + fib(n-2)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Cache decorator - Python

A
def mem(func):
    cached = dict()
    def inner(n):
        if n not in cached:
            cached[n] = func(n)
        return cached[n]    
    return inner

@mem
def fib(n):
if n < 2:
return 1
return fib(n-2) + fib(n-1)
~~~
~~~

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

Prime number checker - Python

A
def is_prime(n):
    if n < 2:
        return False

    for i in filter(lambda x: x % 2 != 0, range(2, int(n**0.5))):
        if n % i == 0:
            return False

    return True

print filter(is_prime, range(100))
~~~
~~~

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

Quick sort - Python

A
def q_sort(a):
    if len(a) in (0, 1):
        return a

    p = a[-1]
    l = [x for x in a[:-1] if x <= p]
    r = [x for x in a[:-1] if x >  p]
return q_sort(l) + [p] + q_sort(r) ~~~ ~~~
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Bubble sort - Python

A
def bubble(l_elems, is_sorted, step):
    if step is 1 or is_sorted:
        return l_elems
    else:
        is_swapped = False
        for i in range(len(l_elems) - 1):
            if l_elems[i] > l_elems[i + 1]:
                is_swapped = True
                l_elems[i], l_elems[i + 1] = l_elems[i + 1], l_elems[i]
        return bubble(l_elems, not is_swapped, step - 1)

print(bubble(range(10,0,-1), False, len(range(10,0,-1))))
print(bubble([5,6,5,3,3], False, len([5,6,5,3,3])))

https://gist.github.com/jootse84/3c51a776471a37beebac10d42ba9f42f

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

Depth First Search - Python

A
graph = {'A': set(['B', 'C']),
         'B': set(['A', 'D', 'E']),
         'C': set(['A', 'F']),
         'D': set(['B']),
         'E': set(['B', 'F']),
         'F': set(['C', 'E'])}

def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for next in graph[start] - visited:
dfs(graph, next, visited)
return visited
~~~

dfs(graph, ‘C’) # {‘E’, ‘D’, ‘F’, ‘A’, ‘C’, ‘B’}
~~~

http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/

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

Breadth First Search - Python

A
graph = {'A': set(['B', 'C']),
         'B': set(['A', 'D', 'E']),
         'C': set(['A', 'F']),
         'D': set(['B']),
         'E': set(['B', 'F']),
         'F': set(['C', 'E'])}

def bfs(graph, start):
visited, queue = set(), [start]
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited
~~~

bfs(graph, ‘A’) # {‘B’, ‘C’, ‘A’, ‘F’, ‘D’, ‘E’}
~~~

http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/

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

Binary search - Python

A
def binarySearch(alist, item):
    first = 0
    last = len(alist)-1
    found = False
while first<=last and not found:
    midpoint = (first + last)//2
    if alist[midpoint] == item:
        found = True
    else:
        if item < alist[midpoint]:
            last = midpoint-1
        else:
            first = midpoint+1 ~~~

return found ~~~

5.4. The Binary Search — Problem Solving with Algorithms and Data Structures

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

Factorial - Python

A
def fact(n):
    if n == 0:
        return 1
    else:
        return n * fact(n-1)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Linear Search - Python

A
def search(arr, x):

    for i in range(len(arr)):

        if arr[i] == x:
            return i

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

Binary tree - Python

A
class Tree(object):
    def \_\_init\_\_(self):
        self.left = None
        self.right = None
        self.data = None

root = Tree()

root. data = “root”
root. left = Tree()
root. left.data = “left”
root. right = Tree()
root. right.data = “right”

print(root.left.data)

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

Tree data - Python

A
from collections import defaultdict

def tree():
    return defaultdict(tree)

or

tree = lambda: defaultdict (tree)

https://gist.github.com/hrldcpr/2012250

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

N-queens problem - Python

A
BOARD_SIZE = 8

def under_attack(col, queens):
return col in queens or \
any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))
~~~

def solve(n):
solutions = [[]]
for row in range(n):
solutions = (solution+[i+1]
for solution in solutions
for i in range(BOARD_SIZE)
if not under_attack(i+1, solution))
return solutions

answers = solve(BOARD_SIZE)
first_answer = next(answers)
print(list(enumerate(first_answer, start=1)))
~~~

https://rosettacode.org/wiki/N-queens_problem#Python

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