예제 #1
0
        if self.is_clear() == False: return False
        # decrement the locked_children attribute of the ancestors
        parent = self.parent
        while parent is not None:
            parent.locked_children = max(parent.locked_children - 1, 0)
            parent = parent.parent
        # self self to unlocked
        self.unlocked = True
        return True


# main
if __name__ == "__main__":
    # input list
    ar = [6, 4, 0, 23, -9, -18, 17]
    # make a small tree and insert stuff into it and lock the middle node
    root = lbt_node(ar[0])
    target = None
    n = len(ar)
    for i in range(1, n):
        cur = root.bst_insert(ar[i])
        if i == n // 2: target = cur
    # lock the target node (succeeds)
    ufunc_eval(target.lock)
    # try to lock its parent (fails)
    ufunc_eval(target.parent.lock)
    # unlock the target node (succeeds)
    ufunc_eval(target.unlock)
    # lock the parent (succeeds)
    ufunc_eval(target.parent.lock)
예제 #2
0

def pi_mc(n=1000000, sig=2, r=1):
    """
    generates a monte carlo estimate of pi by seeing what fraction of generated
    points fall within a circle or radius r out of all the points generated
    within a box of side length 2r, centered at (0, 0). n controls the number of
    points to generate for the estimate. sig indicates to how many decimal
    places the generated estimate should express.
    """
    # number of points that fall within the unit circle
    n_in = 0
    # for n iterations, generate (x, y) pairs where -r <= x <= r, -r <= y <= r
    for i in range(n):
        x = random.uniform(-r, r)
        y = random.uniform(-r, r)
        # if we have that x ^ 2 + y ^ 2 <= r ^ 2, then it is in the unit circle
        # so we increment n_in (number of points in the unit circle)
        if x**2 + y**2 <= r**2: n_in = n_in + 1
    # calculate area of the unit circle (percentage of box area)
    A = (n_in / n) * (4 * r**2)
    # return estimate for pi
    return round(A / (r**2), ndigits=sig)


# main
if __name__ == "__main__":
    # more or less returns ~3.14 as desired. note that having a smaller value of
    # r will lead to a more accurate estimation, holding n constant.
    ufunc_eval(pi_mc, sig=3, r=0.05)
예제 #3
0
        for j in range(min(ar[i], n - i - 1)):
            G[i].append(i + j + 1)
    # now that we have the graph, perform BFS on the graph
    queue = [0]
    while len(queue) > 0:
        u = queue.pop(0)
        # if this is the last node, return True
        if u == n - 1: return True
        # else add all its edges to the queue
        for i in range(len(G[u])):
            queue.append(G[u][i])
    # if we never reached the end, return False
    return False


# main
if __name__ == "__main__":
    func = crossable
    # problem input 1, answer is True
    ar = [2, 0, 1, 0]
    ufunc_eval(func, ar)
    # problem input 2, answer is False
    ar = [1, 1, 0, 1]
    ufunc_eval(func, ar)
    # input 3, answer is False
    ar = [3, 0, 0, 0, 3, 0, 0, 1, 2, 1, 0, 0]
    ufunc_eval(func, ar)
    # input 4, answer is True
    ar = [2, 0, 3, 0, 2, 0, 1, 2, 0, 1, 0]
    ufunc_eval(func, ar)
예제 #4
0
    """
    # sanity check although technically base could be a float too
    assert isinstance(base, int) and isinstance(exp, int)
    # base case: if exp is 0 or 1
    if exp == 0: return 1
    elif exp == 1: return base
    # if exp is odd, we will need to also multiply by base
    extra = 1
    if exp % 2 > 0: extra = base
    # get the square root of base ^ exp
    prod_sqrt = fast_pow(base, exp // 2)
    # return final product
    return extra * prod_sqrt * prod_sqrt


# main
if __name__ == "__main__":
    func = fast_pow
    # problem input, answer is 1024
    base = 2
    exp = 10
    ufunc_eval(func, base, exp)
    # another input, answer is 48828125
    base = 5
    exp = 11
    ufunc_eval(func, base, exp)
    # another input, answer is 117649
    base = 7
    exp = 6
    ufunc_eval(func, base, exp)
예제 #5
0
                                list(tp_dict[cur].keys())[0]),
                      file=stderr)
                return st_dict
            # if the cumulative transition probability is greater than r, mark
            # an additional visit to state k, and set cur to k before break
            if tp > r:
                st_dict[k] = st_dict[k] + 1
                cur = k
                break
        # simulate next transition
    # return st_dict
    return st_dict


# main
if __name__ == "__main__":
    func = run_markov_chain
    # problem input
    start, n_steps = 'a', 5000
    tps = [('a', 'a', 0.9), ('a', 'b', 0.075), ('a', 'c', 0.025),
           ('b', 'a', 0.15), ('b', 'b', 0.8), ('b', 'c', 0.05),
           ('c', 'a', 0.25), ('c', 'b', 0.25), ('c', 'c', 0.5)]
    ufunc_eval(func, start, tps, n_steps=n_steps)
    # markov chain with absorbing state a
    start, n_steps = 'b', 7000
    tps = [('a', 'a', 1), ('b', 'a', 0.1), ('b', 'b', 0.5), ('b', 'c', 0.1),
           ('b', 'd', 0.4), ('c', 'a', 0.2), ('c', 'b', 0.1), ('c', 'c', 0.25),
           ('c', 'd', 0.45), ('d', 'a', 0.1), ('d', 'b', 0.4), ('d', 'c', 0.2),
           ('d', 'd', 0.3)]
    ufunc_eval(func, start, tps, n_steps=n_steps)
예제 #6
0
    """
    to prevent stdout from being filled by line-by-line printouts, i opt to
    return a list of all the moves. the optional arguments st, spt,and  et are
    start, spare, and ending tower respectively; by default they are 1, 2, and
    3, as that is the goal of the game. the moves list holds all the moves; the
    parent call will set it to the empty list. classic recursive solution.
    """
    # if parent call, instantiate moves
    if moves is None: moves = []
    # base case: no disks
    if n == 0: return moves
    # recursive case: output from moving n - 1 to spare tower
    moves = hanoi(n - 1, st=st, spt=et, et=spt, moves=moves)
    # move last disk from start to target tower
    moves.append("moves " + str(st) + " to " + str(et))
    # second recursive case: out from n - 1 to target tower
    moves = hanoi(n - 1, st=spt, spt=st, et=et, moves=moves)
    # return list of moves
    return moves


# main
if __name__ == "__main__":
    func = hanoi
    # problem input
    n = 3
    ufunc_eval(func, n)
    # another input
    n = 7
    ufunc_eval(func, n)
예제 #7
0
    """
    assert iter is not None
    # elements in iter
    outl = []
    # add all elements by using the next() call
    while iter.hasnext() == True:
        outl.append(iter.next())
    # catch the exception
    ooee = None
    try:
        iter.next()
    except OutOfElementsException as e:
        ooee = e
    # return elements and the exception's string message
    return outl, str(ooee)


# main
if __name__ == "__main__":
    # test function that will call next to return all elements and then call
    # next an extra time simply to catch the exception
    func = iterator_2d_test
    # start with problem input
    iter = iterator_2d([[1, 2], [3], [], [4, 5, 6]])
    ufunc_eval(func, iter)
    # test with another input
    iter = iterator_2d([[-4, -3], [], [-2, -1], [0, 1, 2], [], [3], [4]])
    ufunc_eval(func, iter)
    # show what the actual output looks like for the exception
    iter.next()
예제 #8
0
                max_prod = max(max_prod, ar[i] * ar[j] * ar[k])
    return max_prod


def triple_sum_sort(x):
    """
    O(nlogn) solution, slightly better. sort all the elements and then return
    max of product of max three elements and then product of two smallest and
    the max element. this handles the case of negative integers.
    """
    assert (ar is not None) and (len(ar) > 2)
    n = len(ar)
    # sorted array
    sar = sorted(ar)
    # return max
    return max(sar[0] * sar[1] * sar[-1], sar[-3] * sar[-2] * sar[-1])


# main
if __name__ == "__main__":
    func_a = triple_sum_naive
    func_b = triple_sum_sort
    # problem input, answer is 500
    ar = [-10, -10, 5, 2]
    ufunc_eval(func_a, ar)
    ufunc_eval(func_b, ar)
    # random input, answer is 304920
    ar = [-45, 22, -121, 7, -90, -11, -23, 28, 2]
    ufunc_eval(func_a, ar)
    ufunc_eval(func_b, ar)
예제 #9
0
    # sanity checks
    assert n > 0 and x > 0
    # occurrences of x in the table
    freq = 0
    # for each row of the multiplication table
    for i in range(n):
        # check if x is divisible by the row number
        if x % (i + 1) == 0:
            # if so, get the quotient
            k = x // (i + 1)
            # if the quotient is a column in the table, x is in row i
            if (k > 0) and (k < n + 1): freq = freq + 1
    # return freq
    return freq

# main
if __name__ == "__main__":
    func = mt_freq
    # problem input, answer is 4
    n = 6
    x = 12
    ufunc_eval(func, n, x)
    # another input, answer is 0 (since 19 is prime!)
    n = 7
    x = 19
    ufunc_eval(func, n, x)
    # another input, answer is 4
    n = 8
    x = 24
    ufunc_eval(func, n, x)
예제 #10
0
                if mat[init[0] + i][init[1]] != wd[i]: break
                else: mcs = mcs + 1
            if mcs == wd_len: return True
            mcs = 1
    # if we still haven't returned True, we have failed
    return False


# main
if __name__ == "__main__":
    func = find_word
    # problem inputs; answers are True, True
    mat = [['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'],
           ['M', 'A', 'S', 'S']]
    wa = "FOAM"
    wb = "MASS"
    ufunc_eval(func, mat, wa)
    ufunc_eval(func, mat, wb)
    # more inputs; answers are True, True, True, False
    mat = [['a', 'h', 'f', 'c', 't'], ['c', 's', 'r', 'h', 'a'],
           ['a', 'r', 'a', 'e', 'h'], ['d', 'a', 'y', 'e', 's'],
           ['g', 'y', 'b', 's', 'n'], ['z', 'a', 'w', 'e', 'e']]
    wa = "cheese"
    wb = "ara"
    wc = "fray"
    wd = "academy"
    ufunc_eval(func, mat, wa)
    ufunc_eval(func, mat, wb)
    ufunc_eval(func, mat, wc)
    ufunc_eval(func, mat, wd)
예제 #11
0
from random import randint

def randnat(k):
    """
    wrapper around randint that returns with uniform probability an integer x in
    the range of [1, k]. just to make the problem specification explicit.
    """
    return randint(1, k)

def deck_shuffle(n = 52):
    """
    if we shuffle a deck of cards, we are simply permuting it. enough said.
    since randnat() is O(1), this is an O(n) solution.
    """
    # create array of cards, 1 to n
    ar = [i + 1 for i in range(n)]
    # for each index i, select the remaining n - i cards with equal probability
    for i in range(n):
        # select one of the remaining cards (decrease by 1 due to zero-indexing,
        # but offset by i to prevent selection of the previous i
        si = i + randnat(n - i) - 1
        # swap
        ar[i], ar[si] = ar[si], ar[i]
    # return permuted deck
    return ar

# main
if __name__ == "__main__":
    func = deck_shuffle
    ufunc_eval(func)
예제 #12
0
    assert rows > 0 and cols > 0
    # if there is only one row, then there is only one path to the bottom right
    # hand corner (end) of the grid (array).
    if rows == 1: return 1
    # else set up two arrays, one for prev row and one for next row. we could
    # set up an entire matrix, but this is more memory efficient.
    prev = [1 for _ in range(cols)]
    cur = [0 for _ in range(cols)]
    # need to set cur[0] to 1; remember first column is all 1 as well
    cur[0] = 1
    # for each row starting from the second row, starting from col index 1
    for _ in range(1, rows):
        for c in range(1, cols):
            cur[c] = cur[c - 1] + prev[c]
        # swap prev and cur to save on memory realloc costs
        old_prev = prev
        prev = cur
        cur = old_prev
    # return last element in prev
    return prev[cols - 1]

# main
if __name__ == "__main__":
    func = num_paths
    # problem input
    rows, cols = 5, 5
    ufunc_eval(func, rows, cols)
    # simple input, answer is 3
    rows, cols = 2, 3
    ufunc_eval(func, rows, cols)
                    new_node.parent = cur
                    cur.right = new_node
                    break
                # else just go right
                cur = cur.right
    # return root
    return root


# main
if __name__ == "__main__":
    func = get_next_inorder
    # problem input, answer is 30
    root = make_bst([10, 5, 30, 22, 35])
    k = 22
    nin = ufunc_eval(func, root, k)
    print(nin.data if nin is not None else "None")
    # same tree different k, answer is 22
    k = 10
    nin = ufunc_eval(func, root, k)
    print(nin.data if nin is not None else "None")
    # another input, answer is 13
    root = make_bst([8, 10, 9, 7, 4, 13, 12, 20])
    k = 10
    nin = ufunc_eval(func, root, k)
    print(nin.data if nin is not None else "None")
    # same tree different k, answer is None
    k = 20
    nin = ufunc_eval(func, root, k)
    print(nin.data if nin is not None else "None")
예제 #14
0
            ca[ci] = ca[ci] + 1
            ei = ei + 1
        # else dcn > k, so start advancing si instead.
        else:
            # get char's index in ca
            ci = ord(s[si]) - 97
            # decrease char count in ca
            ca[ci] = ca[ci] - 1
            # if ca[ci] == 0, then decrement dcn
            if ca[ci] == 0: dcn = dcn - 1
            # increment si
            si = si + 1
    # if dcn <= k, take max of maxl and ei - si
    if dcn <= k: maxl = max(maxl, ei - si)
    return maxl


def g(x):
    """
    description of solution runtime and any other comments. usually necessary
    because follow up question are often asked.
    """
    return False


# main
if __name__ == "__main__":
    s = "abcbaffffvbfffff"
    k = 3
    ufunc_eval(kcharstr, s, k)
예제 #15
0
copy the problem starting with the sentence 'This problem was asked by xxx
company', and then insert a blank line between that sentence and the body of the
question. get rid of all other extra line breaks. the question statement should
be in proper sentence case unlike this docstring. this template should be reused
for all problems from daily coding problem. note that the help utility will only
wrap lines that are too long, hence the newline before the doc text starts.
"""

# import evaluation function
from ufunc_eval import ufunc_eval

def f(x):
    """
    description of solution runtime and any other comments.
    """
    return True

def g(x):
    """
    description of solution runtime and any other comments. usually necessary
    because follow up question are often asked.
    """
    return False

# main
if __name__ == "__main__":
    # remove all comments in main body later
    l = 10 # and any other inputs
    func = f # set function you want to test
    ufunc_eval(func, l) # print output
예제 #16
0
import sys
# import evaluation function
from ufunc_eval import ufunc_eval


def xorll_test(exe_name, A):
    """
    wrapper for the implementation; runtime not relevant here. takes a string,
    which should be the name of the external executable that test the C
    implementation of an xor linked list, and a list of integers. note that the
    C function atoi(), which is used to parse the string arguments into ints,
    returns 0 if it cannot parse a string into an int, and also has a fixed size
    on how large the int can be. so please keep ints under 32-bit signed.
    """
    if (exe_name is None) or (exe_name == ""):
        print("{0}: error: empty executable name".format(xorll_test.__name__),
              file=sys.stderr)
        quit(1)
    # convert all elements in A to strings (for sanity purposes)
    for i in range(len(A)):
        A[i] = str(A[i])
    # run and return stdout; strip extra newline from output
    cp = subprocess.run([exe_name] + A, capture_output=True, text=True)
    return cp.stdout.rstrip()


# main
if __name__ == "__main__":
    A = [3, 4, 2, 34, -2, 43, -98, 11]
    ufunc_eval(xorll_test, "./xorll/main.exe", A)  # print output
예제 #17
0
    # get lengths of a and b
    na, nb = len(a), len(b)
    # if they don't match, not onto so return False
    if na != nb: return False
    # else start biulding the dictionary of mappings
    mdict = {}
    for i in range(na):
        # if there is a mapping for a[i] in mdict
        if a[i] in mdict:
            # if the mapping matches a[i] -> b[i], then pass
            if mdict[a[i]] == b[i]: pass
            # else return False; no bijection
            else: return False
        # else no mapping for character a[i], so add map a[i] -> b[i] to mdict
        else: mdict[a[i]] = b[i]
    # return True if we made it all the way through the string
    return True

# main
if __name__ == "__main__":
    func = has_bijective_map
    # problem input, answer is True
    a, b = "abc", "bcd"
    ufunc_eval(func, a, b)
    # another problem input, answer is False
    a, b = "foo", "bar"
    ufunc_eval(func, a, b)
    # another input, answer is False (no onto mapping)
    a, b = "foo", "baabaablacksheep"
    ufunc_eval(func, a, b)
예제 #18
0
        # if its depth is greater than that of the deepest, update deepest
        if ud > ddepth: deepest, ddepth = u, ud
        # else do nothing; add all non-null nodes to queue
        if u.left is not None: queue.append((u.left, ud + 1))
        if u.right is not None: queue.append((u.right, ud + 1))
    # return deepest node
    return deepest


# main
if __name__ == "__main__":
    func = get_deepest
    # problem input, answer is d
    root = bt_node('a',
                   left=bt_node('b', left=bt_node('d')),
                   right=bt_node('c'))
    deepest = ufunc_eval(func, root)
    print(deepest.data)
    # another tree, answer is -10
    root = bt_node(4,
                   left=bt_node(-4,
                                left=bt_node(31),
                                right=bt_node(14, left=bt_node(19))),
                   right=bt_node(11,
                                 left=bt_node(-11,
                                              right=bt_node(
                                                  -9, left=bt_node(-10))),
                                 right=bt_node(19, left=bt_node(14))))
    deepest = ufunc_eval(func, root)
    print(deepest.data)
예제 #19
0
        else:
            outs = outs + str(ar[i].data)
        # if the index is not the last index, at comma and space
        if i < n - 1: outs = outs + ", "
    # add closing bracket based on instance type
    outs = outs + (")" if isinstance(ar, tuple) else "]")
    # return outs
    return outs


# main
if __name__ == "__main__":
    func_a = two_sum
    func_b = two_sum_fast
    # problem input, answer is 5, 15
    root = bt_node(10,
                   left=bt_node(5),
                   right=bt_node(15, left=bt_node(11), right=bt_node(15)))
    k = 20
    print(bt_list_str(ufunc_eval(func_a, root, k)))
    print(bt_list_str(ufunc_eval(func_b, root, k)))
    # another input, answer is 15, 15
    root = bt_node(17,
                   left=bt_node(9,
                                left=bt_node(8),
                                right=bt_node(15, right=bt_node(15))),
                   right=bt_node(20, right=bt_node(24)))
    k = 30
    print(bt_list_str(ufunc_eval(func_a, root, k)))
    print(bt_list_str(ufunc_eval(func_b, root, k)))
예제 #20
0
        # coords of ith point
        xi, yi = pts[i]
        # get abs differences in x, y coordinates
        dx, dy = abs(xi - x), abs(yi - y)
        # if dx is 0, add dy to ns
        if dx == 0:
            ns = ns + dy
            # else if y is 0, add dx to ns
        elif dy == 0:
            ns = ns + dx
            # else neither are 0; add min(dx, dy) to ns, and for whichever is chosen
            # subtract that from the other d*, then add the remaining to ns. this
            # whole process is the same as adding max(dx, dy) to ns
        else:
            ns = ns + max(dx, dy)
        # update position
        x, y = xi, yi
    # return ns
    return ns


# main
if __name__ == "__main__":
    func = min_steps
    # problem input, answer is 2
    pts = [(0, 0), (1, 1), (1, 2)]
    ufunc_eval(func, pts)
    # another input, answer is 24
    pts = [(3, 9), (-1, 3), (8, 7), (-1, 2)]
    ufunc_eval(func, pts)
예제 #21
0
    technically still O(n) due to preprocessing of the array, but the selection
    of the nearest index is O(1) due to lookup in a dictionary.
    """
    assert (ar is not None) and (len(ar) > 0) and (t >= 0)
    # length of array
    n = len(ar)
    # index of nearest largest, distance from l to t
    l = None
    dl = inf
    # preprocess by looping through the array and comparing distance
    for i in range(n):
        if (ar[i] > ar[t]) and (i - t < dl): l, dl = i, abs(i - t)
    # return l (could be None; technically this is O(1) i guess)
    return l


# main
if __name__ == "__main__":
    func_a = nearest_slow
    func_b = nearest_fast
    # problem input, answer is 3
    ar = [4, 1, 3, 5, 6]
    t = 0
    ufunc_eval(func_a, ar, t)
    ufunc_eval(func_b, ar, t)
    # another input, answer is None
    ar = [5, 1, 6, 5, 13, 8, 2, 9, 7]
    t = 4
    ufunc_eval(func_a, ar, t)
    ufunc_eval(func_b, ar, t)
예제 #22
0
    """
    description of solution runtime and any other comments. usually necessary
    because follow up question are often asked.
    """
    return False

# main
if __name__ == "__main__":
    func = cw_spiral
    # problem input, answer is [1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11,
    # 6, 7, 8, 9, 14, 13, 12]
    mat = [[1,  2,  3,  4,  5],
           [6,  7,  8,  9,  10],
           [11, 12, 13, 14, 15],
           [16, 17, 18, 19, 20]]
    ufunc_eval(func, mat)
    # another input, answer is [5, 4, 7, -1, 12, -5, 11, 98, 67, -4, 41, -1, 12,
    # -98, -2, -1, 2, 4, 23, 6, 23, 23, 11, 15]
    mat = [[5, 4, 7],
           [4, 23, -1],
           [2, 6, 12],
           [-1, 23, -5],
           [-2, 23, 11],
           [-98, 11, 98],
           [12, 15, 67],
           [-1, 41, -4]]
    ufunc_eval(func, mat)
    # another input, answer is [9, 8, 1, -8, 15, 14, 11, -2, 5]
    mat = [[9, 8, 1],
           [-2, 5, -8],
           [11, 14, 15]]
예제 #23
0
    nca = len(stk)
    # number of open parentheses to prepend, number of closes to append
    nop, ncl = 0, 0
    # for each element in the stack
    for e in stk:
        # if e is open, we need to append a close, so increment ncl
        if e == "(":
            ncl = ncl + 1
            # else if e is closed, we need to prepend an open, so increment nop
        elif e == ")":
            nop = nop + 1
    # return balanced string and nca
    return (nop * "(") + s + (ncl * ")"), nca


# main
if __name__ == "__main__":
    func = min_balance
    # problem input, answer is ("(())", 1)
    s = "(()"
    ufunc_eval(func, s)
    # another problem input, [an] answer is ("(())()()", 3)
    s = "))()("
    ufunc_eval(func, s)
    # another input, answer is ("(())()(())", 0)
    s = "(())()(())"
    ufunc_eval(func, s)
    # another input, answer is ("((())()(()))(()()())", 5)
    s = "))()(()))(()()("
    ufunc_eval(func, s)
예제 #24
0
    """
    # note that n is the chessboard dimension, and bl is the list of bishops
    assert (bl is not None) and (n > 0)
    # get length of the bishop list
    k = len(bl)
    # number of pairs attacking each other (through other pieces as well)
    pairs = 0
    # check each combination of bishops
    for i in range(k):
        ba = bl[i]
        for j in range(i + 1, k):
            bb = bl[j]
            # if x and y displacements are equal in magnitude, the two bishops
            # in question are definitely on the same diagonal
            if abs(ba[0] - bb[0]) == abs(ba[1] - bb[1]): pairs = pairs + 1
    return pairs


# main
if __name__ == "__main__":
    func = bishop_attacks
    # problem input, answer is 2
    bl = [(0, 0), (1, 2), (2, 2), (4, 0)]
    n = 5
    ufunc_eval(func, bl, n)
    # another input, answer is 4
    bl = [(0, 0), (0, 5), (1, 0), (2, 3), (2, 5), (4, 1), (5, 3), (6, 0),
          (6, 5)]
    n = 7
    ufunc_eval(func, bl, n)
예제 #25
0
    # assume that the matrix is a square matrix
    n = len(mat)
    # transpose the matrix
    for i in range(n):
        for j in range(i + 1, n):
            mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
    # swap the columns of the matrix
    for i in range(n):
        for j in range(n // 2):
            mat[i][j], mat[i][n - j - 1] = mat[i][n - j - 1], mat[i][j]
    # if as_str is True, return as a nice formatted string
    if as_str == True: return str(mat).replace("], [", "],\n [")
    # else return mat (although modified in place)
    return mat


# main
if __name__ == "__main__":
    func = rotate_cw
    # problem input, answer is [[7, 4, 1],
    #                          [8, 5, 2],
    #                          [9, 6, 3]]
    mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    ufunc_eval(func, mat, as_str=True)
    # another input, answer is [[-9, 3, 1, 5],
    #                          [-6, -3, 5, -4],
    #                          [0, 8, 99, 7],
    #                          [4, -5, 2, -1]]
    mat = [[5, -4, 7, -1], [1, 5, 99, 2], [3, -3, 8, -5], [-9, -6, 0, 4]]
    ufunc_eval(func, mat, as_str=True)
예제 #26
0
def nearest(pts, cp, k):
    """
    given a list of (x, y) tuples pts, a central tuple cp, and k > 0, returns
    the nearest k points to the central tuple by sorting using euclidean
    distance from cp as the criteria for sorting, so O(nlogn). clearly, however,
    for small k this is slower than linear search.
    """
    assert (pts is not None) and (cp is not None) and (k > 0)
    # get length of pts
    n = len(pts)
    # edge cases
    if (n == 0) or (k > n): return None
    # get new list of points, sorted by distance from cp
    spts = sorted(pts, key = lambda a: sqrt((a[0] - cp[0]) ** 2 +
                                            (a[1] - cp[1]) ** 2))
    # return the first k
    return spts[:k]

# main
if __name__ == "__main__":
    func = nearest
    # problem input, answer is [(0, 0), (3, 1)]
    pts = [(0, 0), (5, 4), (3, 1)]
    cp, k = (1, 2), 2
    ufunc_eval(func, pts, cp, k)
    # another input, answer is [(0, 0), (-2, 1), (-2, -2), (2, 3), (-1, 4)]
    pts = [(1, 5), (2, 3), (-1, 4), (4, -1), (-2, -2), (0, 0), (-2, 1), (3, 4)]
    cp, k = (0, 0), 5
    ufunc_eval(func, pts, cp, k)
예제 #27
0

def jobdelay(func, w, *args, **kwargs):
    """
    trivial implementation of what was asked. not sure if this is what was
    supposed to be the answer to the problem. takes function func, will delay
    it by w milliseconds, before executing func. takes any other unnamed and
    named arguments that func takes, passing them to func
    """
    # sanity checks
    if func is None: return None
    if w < 0:
        raise ValueError("{0}: positive delay required"
                         "".format(jobdelay.__name__))
    # sleep w milliseconds
    time.sleep(w / 1000)
    return func(*args, **kwargs)


# random test function
def _f(x, y, a=-1, b=-2):
    return pow(x * y, a ^ b)


# main
if __name__ == "__main__":
    args = [0.7, 0.9]
    kwargs = {"a": 17, "b": 8}
    w = 190  # in milliseconds
    ufunc_eval(jobdelay, _f, w, *args, **kwargs)
예제 #28
0
            outl[c] = outl[c] + mp[s[i]][j]
            # if c + 1 % mreps[i] == 0, increment j if (j + 1) < len(mp[s[i]]),
            # else reset j to 0 again
            if (c + 1) % mreps[i] == 0:
                jl = len(mp[s[i]])
                if (j + 1) < jl: j = j + 1
                else: j = 0
    # return outl
    return outl


# main
if __name__ == "__main__":
    func = all_maps
    # truncated problem input (smaller mapping), answer is ["ad", "ae", "af",
    # "bd", "be", "bf", "cd", "ce", "cf"]
    mp = {"2": ["a", "b", "c"], "3": ["d", "e", "f"]}
    s = "23"
    ufunc_eval(func, mp, s)
    # another input, answer is ["iaf", "iag", "iah", "ibf", "ibg", "ibh", "icf",
    # "icg", "ich", "jaf", "jag", "jah", "jbf", "jbg", "jbh", "jcf", "jcg", "jch"]
    mp = {
        "1": ["a", "b", "c"],
        "2": ["d", "e"],
        "3": ["f", "g", "h"],
        "4": ["i", "j"],
        "5": ["k"]
    }
    s = "413"
    ufunc_eval(func, mp, s)
예제 #29
0
        if len(qcur) == 0:
            qcur = qnext
            qnext = []
            lvl = lvl + 1
            look[lvl] = 0
    # return level with lowest sum; in the case of levels having the same sum,
    # the shallowest level will be preferred.
    min_l, min_s = 0, inf
    for k, v in look.items():
        if v < min_s: min_l, min_s = k, v
    return min_l


# main
if __name__ == "__main__":
    func = min_level_sum
    # input 1, answer is 3
    root = bt_node(-5,
                   left=bt_node(8, left=bt_node(-1), right=bt_node(-4)),
                   right=bt_node(-10, left=bt_node(10), right=bt_node(-100)))
    ufunc_eval(func, root)
    # input 2, answer is 4
    root = bt_node(40,
                   left=bt_node(-8,
                                left=bt_node(-4),
                                right=bt_node(14, left=bt_node(-8))),
                   right=bt_node(10,
                                 left=bt_node(-5),
                                 right=bt_node(8, right=bt_node(-16))))
    ufunc_eval(func, root)
예제 #30
0
    for i in range(n // 2):
        wl[i], wl[n - i - 1] = wl[n - i - 1], wl[i]
    # starting and ending indices of each chunk of characters to reverse
    si = ei = 0
    # for each chunk of non-whitespace characters (assumes no leading spaces)
    for i in range(n + 1):
        # stop at whitespace or if we are past last character of the string
        if (i == n) or (wl[i] == " "):
            # reverse indices in the substring, indices si to i - 1
            for j in range(si, (si + i) // 2):
                wl[j], wl[si + i - j - 1] = wl[si + i - j - 1], wl[j]
            # set si to i + 1
            si = i + 1
        # else do nothing
    # join wl and return
    return "".join(wl)


# main
if __name__ == "__main__":
    func_a = word_reverse
    func_b = word_reverse_inplace
    # problem input, answer is "here world hello"
    s = "hello world here"
    ufunc_eval(func_a, s)
    ufunc_eval(func_b, s)
    # another input, answer is "now doing you are what"
    s = "what are you doing now"
    ufunc_eval(func_a, s)
    ufunc_eval(func_b, s)