Code Snippets !

Sudipta Karmakar
writes jibber-jabber for living
binges books, music, movies
sports enthusiast, football fanatic
Bash Color Output

This is an example of how output text color can be modified in bash. Here is the main source from Stack Overflow. List of ANSI escape codes here.

# Color codes
Black        0;30     Dark Gray     1;30
Red          0;31     Light Red     1;31
Green        0;32     Light Green   1;32
Orange       0;33     Yellow        1;33
Blue         0;34     Light Blue    1;34
Purple       0;35     Light Purple  1;35
Cyan         0;36     Light Cyan    1;36
Light Gray   0;37     White         1;37
# Example:
NC='\033[0m' # No Color
printf "I ${RED}love${NC} New York\n"
Ackermann Function

Python implementation of Ackermann function

cache = {}
def ack(m, n):
    """Computes Ackermann function A(m, n)
    :param n, m: non-negative integers
    if cache.get((m, n)) is not None: return cache.get((m, n))
    if m == 0: cache[(m, n)] = n + 1; return n + 1
    if n == 0: cache[(m, n)] = ack(m-1, 1); return cache[(m, n)]
    cache[(m, n)] = ack(m-1, ack(m, n-1))
    return cache[(m, n)]
Connected Components in a Graph

Python implementation of finding the number of connected components in a Graph

class Node(object):
   def __init__(self, value):
       self.visited = False
       self.connected_to = set()
   def connect(self, *nodes):
   def neighbors(self):
       for node in self.connected_to:
           yield node
def dfs(node):
   for neighbor in node.neighbors():
       if neighbor.visited : continue
       neighbor.visited = True
def get_components(graph):
   components = 0
   for node in graph:
       if node.visited: continue
       node.visited = True
       components += 1
   return components

👍  Special thanks to the good people at Skeleton!