Skip to content

Instantly share code, notes, and snippets.

from collections import defaultdict as dd
from itertools import product
def solve(limit, values, weights):
""" Solution for the unbounded knapsack problem. """
weights, values = zip(*sorted([(w, v) for w, v in zip(weights, values)]))
inf = limit + 1
maxv = [0 for _ in xrange(limit + 1)]
for value, weight in zip(values, weights):
from fractions import Fraction as F
class NotSolved(Exception):
pass
def odd_solve(t):
coll = []
zero = F(0, 1)
from fractions import Fraction as F, gcd
from os import environ as env
__all__ = ["greedy_solve"]
def _find_next(t, c):
p = c
zero = F(0, 1)
while t - F(1, c) < zero:
def has_directed_cycle(graph):
for node in graph.iterkeys():
frontline = [node]
was = set([node])
while frontline:
curr = frontline.pop()
if curr in was:
continue
was.add(curr)
for neighbor in graph[curr]:
@jakab922
jakab922 / parse_flags.py
Created December 3, 2016 19:17
Parsing flags for the smartcab assignment
def parse_flags():
from optparse import OptionParser
usage = "usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option(
"-v", "--verbose", dest="verbose",
help="set to True to display additional output from the simulation",
action="store_true", default=False)
parser.add_option(
"--num_dummies", dest="num_dummies",
@jakab922
jakab922 / egg_and_floors.py
Last active February 7, 2017 14:04
Solution to the eggs and floors puzzle. The original asks that if you have a 100 floors and 2 eggs what' the minimum number of drops needed to figure out where the eggs break.
from math import sqrt, ceil
from functools import wraps
from optparse import OptionParser
CACHE = {}
def cache(f):
@wraps(f)
def cached(*args, **kwargs):
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool sol(string& s) {
bool total[26];
fill_n(&total, 26, false);
for(char& c : s) {
@jakab922
jakab922 / rbt.pyx
Created March 2, 2017 17:11
Red and black tree insert operation implemented. It's an order of magnitude slower than the stl set so I guess there is space for improvement.
#!python
#cython: boundscheck=False, wraparound=False, initializedcheck=False
from cpython cimport bool
LEFT, RIGHT = range(2)
RED, BLACK = range(2)
cocodes = ["R", "B"]
chcodes = ["l", "r"]
@jakab922
jakab922 / blackjack.py
Created March 30, 2017 15:52
Command line blackjack game
from random import shuffle, randint as ri
from itertools import product
PLAYER, OP, BOTH, NEITHER = range(4)
suits = ["clubs", "diamonds", "hearts", "spades"]
values = [
"ace", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten",
"jack", "queen", "king"]
@jakab922
jakab922 / rbt_half_baked.py
Created April 3, 2017 10:24
Half baked red and black tree
RED, BLACK = range(2)
LEFT, RIGHT = range(2)
SMALLER, EQUAL, BIGGER = range(-1, 2)
def _set_relation(child, parent, rtype):
if child is not None:
child.parent = parent
if parent is not None:
if rtype == LEFT: