Exemple #1
0
def findRotateSteps(ring,key):
    from collections import defaultdict as d
    choices = d()
    for k in key:
        if k in choices:
            continue
        else:
            choices[k] = []
            for ri, r in enumerate(ring):
                if r == k:
                    choices[k].append(ri)
    counter = [{0: 0}]
    path = d()
    for keyi in range(len(key)):
        counter.append({})
        for choice in choices[key[keyi]]:
            temp = []
            for start in counter[keyi].keys():
                previous_choice = counter[keyi][start]
                s = str(start) + '-' + str(choice)
                if s not in path:
                    d1 = abs(choice - start)
                    d2 = abs(len(ring) - d1)
                    newc = min(d1, d2)
                    path[s] = newc
                temp.append(previous_choice + path[s])
            counter[keyi + 1][choice] = min(temp) + 1
    final = min(counter[-1].values())
    return final
Exemple #2
0
    def solveSudoku(self, board):
        from collections import defaultdict as d
        rows, cols, triples, tofill = d(set), d(set), d(set), []
        for r in range(9):
            for c in range(9):
                x, t = board[r][c], (r // 3, c // 3)
                if x != ".":
                    rows[r].add(x)
                    cols[c].add(x)
                    triples[(r // 3, c // 3)].add(x)
                else:
                    tofill.append((r, c, t))

        def dfs():
            #print(board[-1])
            if not tofill:
                return True
            r, c, t = tofill[-1]
            for dig in "123456789":
                if dig not in rows[r] | cols[c] | triples[t]:
                    board[r][c] = dig
                    rows[r].add(dig)
                    cols[c].add(dig)
                    triples[t].add(dig)
                    tofill.pop()
                    if dfs(): return True
                    board[r][c] = "."
                    rows[r].discard(dig)
                    cols[c].discard(dig)
                    triples[t].discard(dig)
                    tofill.append((r, c, t))
            return False

        dfs()
Exemple #3
0
def pijmatrix(MC, np):
    from collections import defaultdict as d
    jb = min([MC, np])
    Matrix = d(lambda: d(float))
    #print np
    Matrix[0][0] = 1.0
    for i in range(1, MC + 1):
        for j in range(1, jb + 1):
            t1 = ((1 + np - j) / float(np)) * Matrix[i - 1][j - 1]
            t2 = (j / float(np)) * Matrix[i - 1][j]
            pij = t1 + t2
            Matrix[i][j] = pij

    return Matrix
Exemple #4
0
def longestCommonSubstring(s, t):
    if not set(s).intersection(set(t)):
        return 0
    from collections import defaultdict as d
    a = d(list)
    for i in xrange(len(t)):
        a[t[i]].append(i)
    m = 0
    i = 0
    while i < len(s):
        #print 'a'
        if s[i] in a:
            j = i + 1
            x = a[s[i]]
            k = 1
            while x and j < len(s):
                t = s[j]
                #print x,j,k,t,a[t]
                if t in a:
                    x = [y + 1 for y in x if y + 1 in a[t]]
                    if not x:
                        break
                    else:
                        m = max(m, k)
                else:
                    #i = j
                    break
                j += 1
                k += 1
        i += 1
    return m + 1
Exemple #5
0
def solution(n, computers):
    #그래프 노드 생성  EX) graph={1 : [1,2], 2 : [1,2], 3 : [3]}
    graph = d(list)
    for i in range(n):
        for idx, j in enumerate(computers[i], 1):
            if j == 1:
                graph[i + 1].append(idx)
    visit = []
    count = 0
    #1번 노드부터 탐색
    for i in range(1, n + 1):
        q = deque()
        q.extend(graph[i])
        flag = False
        #연결된 모든 노드를 visit에 저장
        while q:
            node = q.popleft()
            #노드가 visit에 없을 경우 새로운 네트워크
            if node not in visit:
                #해당 노드에 저장된 모든 노드들을 visit에 저장
                visit.append(node)
                q.extend(graph[node])
                flag = True
        #새 네트워크를 찾았을 경우 1증가
        if flag:
            count += 1
    return count
Exemple #6
0
def pjCircle(s, w):
    q = d(range(1, s + 1))
    a = []
    while q:
        q.rotate(-2)
        a.append(q.pop())
    return a[-w:]
Exemple #7
0
def string2freqh(x):
    ''' convert string of nucleotides to dictionary of freqencies'''
    from collections import defaultdict as d

    counts = d(int)
    alleles = ["A", "T", "C", "G"]
    for a in alleles:
        if x.count(a) == 0:
            continue
        counts[a] = x.count(a)

    h = d(float)
    for k, v in counts.items():
        h[k] = v / float(len(x))

    return h, len(x)
Exemple #8
0
def string2freqh(x):
    ''' convert string of nucleotides to dictionary of freqencies where x is a string of nucleotides'''
    from collections import defaultdict as d
    if x == "" or x == "na":
        return "na", "na"
    counts = d(int)
    nuc = ["A", "T", "C", "G"]
    for u in nuc:
        if x.count(u) == 0:
            continue
        counts[u] = x.count(u)

        h = d(float)
        for k, v in counts.items():
            h[k] = v / float(sum(counts.values()))
    return h, sum(counts.values())
def expandMinesweeper(field, click_row, click_column):
    # return the field as-is if the clicked cell is NOT empty
    if field[click_row][click_column] != 0:
        return field

    # dim
    w = len(field[0])
    h = len(field)

    # typical bfs
    q = d([[click_row, click_column]])
    v = set()  # visited nodes

    while q:
        y, x = q.popleft()  # and not pop(0) for lists
        v.add((y, x))  # mark as visited

        field[y][x] = -2  # modify

        for dy in range(-1, 2):
            for dx in range(-1, 2):
                # new coordinates
                ny = y + dy
                nx = x + dx

                if ny < 0 or ny >= h or nx < 0 or nx >= w or (
                        ny, nx) in v or field[ny][nx] != 0:
                    continue

                v.add((ny, nx))
                q.append((ny, nx))  # next node to visit

    # return the new field
    return field
Exemple #10
0
def counth2freqh(x):
    ''' calculate freq-list from counts in dictionary'''
    from collections import defaultdict as d

    h = d(float)
    for k, v in x.items():
        h[k] = v / float(sum(x.values()))
    return h, sum(x.values())
Exemple #11
0
def checkUnique() :
    s        : str  = input()
    chardict : d    = d(int)

    for char in s :
        if (chardict[char]) :
            return False
        chardict[char] = 1
    return True
def S(x,y,z,w):
 if(x,y)==(z,w):return 0
 C=[[Z]*8for _ in range(8)];C[x][y]=0;q=d();q.append((x,y))
 while q:
  J,K=q.popleft()
  for i in range(8):
   N,M=J+X[i],K+Y[i]
   if V(N,M)and C[N][M]>C[J][K]+1:
   	C[N][M]=C[J][K]+1
	q.append((N,M))
 return C[z][w]
Exemple #13
0
def solve_case(case):
    N = case['N']
    P = case['P']
    Gs = case['Gs']
    if type(Gs) == int:
        Gs = [Gs]
    Ms = d([g % P for g in Gs])
    if P == 2:
        return Ms[0] + math.ceil((Ms[1] / 2.0))
    if P == 3:
        return Ms[0] + min(Ms[1], Ms[2]) + math.ceil(abs(Ms[1] - Ms[2]) / 3.0)
 def match(self, guns, bullet):
 	from collections import deque as d 
 	q = d(bullet)
 	for i in range(0,len(q)):
 		test = self.check(list(q),list(guns))
 		if test != -1:
 			return test
 		else:
 			ele = q.popleft()
 			q.append(ele)
 	return -1
Exemple #15
0
    def sortByBits(self, arr):
        if not arr: return []

        d1 = d(list)
        for i in arr:
            d1[bin(i).count('1')].append(i)  #bin()的返回类型是str
        d1 = sorted(d1.items(), key=lambda x: x[0])
        res = []
        for key, val in d1:
            res.extend(sorted(val))
        return res
 def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
     # ---- O(n^2) solution -----
     a, b = self.getindices(A), self.getindices(B)
     res = 0
     translationcost = d(int)
     for i in a:
         for j in b:
             cost = (j[0] - i[0], j[1] - i[1])
             translationcost[cost] += 1
             res = max(res, translationcost[cost])
     #print(translationcost)
     return res
Exemple #17
0
def parse_gum(gum):
    from collections import defaultdict as d
    start0, end0, start1, end1 = d(list), d(list), d(list), d(list)
    macro = {}
    info = {}
    uid0, uid1 = d(list), d(list)
    cur = {'start': start0, 'end': end0, 'uid': uid0, 'v': '0'}
    for l in gum.splitlines():
        if l == '-----':
            cur = {'start': start1, 'end': end1, 'uid': uid1, 'v': '1'}
            continue
        uid, start, end, action, mid, title, aux = l.split(' ', 6)
        uid, start, end, = int(uid), int(start), int(end)
        if mid != 'NA':
            mid = int(mid)
            cur['start'][start].append('<span id="map-{}-{}"></span>'.format(
                cur['v'], mid))
        cur['start'][start].append(
            '<span class="{}" id="act-{}" title="{}" data-map="{}">'.format(
                action, uid, title, mid))
        cur['end'][end].append('</span>')
        if aux != '' and aux != '()':
            macro[uid] = (aux, cur['v'])
        info[uid] = (start, end, action, mid, title)
        cur['uid'][start].append(uid)
    return start0, end0, start1, end1, macro, uid0, uid1, info
Exemple #18
0
def lcss(s1,s2):
    assert len(s1)==len(s2)
    pr1=pr2=0
    difd=d(lambda : -1)
    ml=0
    for i in range(len(s1)):
        pr1+=int(s1[i])
        pr2+=int(s2[i])
        cdif=pr1-pr2 
        if cdif==0: ml=i+1 
        elif difd[cdif]==-1: difd[cdif]=i
        else: ml=max(ml,i-difd[cdif])
    return ml 
Exemple #19
0
    def reversePrint(self, head: ListNode) -> List[int]:
        if not head:
            return []
        if not head.next:
            return [head.val]

        from collections import deque as d
        ret = d()
        current = head
        while current:
            ret.appendleft(current.val)
            current = current.next
        return list(ret)
Exemple #20
0
def test_zip():
    tree1 = PlainGraphNode.build(d([
        ('_self', 'Root'),
        ('a', d([
            ('_self', 'Value A'),
            ('a-1', 'Value A-1'),
        ])),
        ('b', 'Value B')
    ]))
    tree2 = PlainGraphNode.build(d([
        ('_self', "Root'"),
        ('a', "Value A'"),
        ('c', "Value C'"),
    ]))


    union = PlainGraphNode.build(d([
        ('_self', ("Root", "Root'")),
        ('a', d([
            ('_self', ("Value A", "Value A'")),
            ('a-1', ("Value A-1", None)),
        ])),
        ('b', ("Value B", None),),
        ('c', (None, "Value C'"),),
    ]))

    intersection = subgraph(union, {'a':[]})
    first = subgraph(union, ['a', 'b'])
    last = subgraph(union, d([
        ('a', []),
        ('c', True),
    ]))

    assert vgz.izip(tree1, tree2, merge_fn='union').all_equals(union)
    assert vgz.izip(tree1, tree2, merge_fn='intersection').all_equals(intersection)
    assert vgz.izip(tree1, tree2, merge_fn='first').all_equals(first)
    assert vgz.izip(tree1, tree2, merge_fn='last').all_equals(last)
    assert vgz.zip(tree1, tree2).all_equals(vgz.izip(tree1, tree2))

    with expecting(vgz.StructureMismatch):
        vgz.zip(tree1, tree2, merge_fn='strict')

    vgz.zip(tree1, tree1, merge_fn='strict')

    t1, t2 = vgz.unzip(vgz.zip(tree1, tree2, merge_fn='union'))
    assert ascii_tree(t1).strip() == textwrap.dedent('''
    root: 'Root'
      +--a: 'Value A'
      |  +--a-1: 'Value A-1'
      +--b: 'Value B'
      +--c: None
    ''').strip()
    assert ascii_tree(t2).strip() == textwrap.dedent('''
    root: "Root'"
      +--a: "Value A'"
      |  +--a-1: None
      +--b: None
      +--c: "Value C'"
    ''').strip()
Exemple #21
0
    def kClosest(self, points, K: int):
        if not points or not K: return []

        dict = d(list)

        for i in points:
            lenght = math.sqrt(i[0]**2 + i[1]**2)
            dict[lenght].append(i)
        dict = sorted(dict.items(), key=lambda x: x[0])
        res = []
        for item in dict:
            res.extend(item[1])
        len_res = len(res)
        return res[:K]
Exemple #22
0
def sync2freqh(x):
    ''' convert string in SYNC format to dictionary of freqencies where x is a string in sync format'''
    from collections import defaultdict as d

    nuc = ["A", "T", "C", "G"]
    counts = map(int, x.split(":")[:4])
    CO = dict(zip(*[nuc, counts]))
    h = d(float)
    if sum(CO.values()) == 0:
        return "NA"
    for k, v in CO.items():
        h[k] = v / float(sum(CO.values()))

    return h, sum(CO.values())
Exemple #23
0
    def __init__(self, switchMapF):
        from collections import OrderedDict as d
        import functools

        def prepare(tupl):
            """(1,2,3) gets split into ((1,2), 3) as preparation for Ordered dict
            This is to make it easiyer for the writer to write"""
            return (tupl[:len(tupl) - 1], tupl[len(tupl) - 1])

        self._ = "____extremelyUnlikeLyString_"
        self.switchList = switchMapF(self._)
        fistTupleLength = len(self.switchList[0])
        assert functools.reduce(
            lambda acc, v: (len(v) == fistTupleLength) and acc,
            self.switchList), "All Condition Tuples must have the same length"
        self.switchMap = d(map(prepare, self.switchList))
Exemple #24
0
def sync2freqh(x):
    ''' convert string in SYNC format to dictionary of freqencies where x is a string in sync format'''
    from collections import defaultdict as d
    if x == ".:.:.:.:.:." or x == "0:0:0:0:0:0":
        return ({"A": "na", "T": "na", "C": "na", "G": "na"}, 0)
        return "na", "na"
    nuc = ["A", "T", "C", "G"]
    counts = [int(X) for X in x.split(":")[:4]]
    if sum(counts) == 0:
        return ({"A": 0.0, "T": 0.0, "C": 0.0, "G": 0.0}, 0)
    CO = {X: Y for X, Y in zip(*[nuc, counts])}
    #print(CO, list(zip(*[nuc,counts])))
    h = d(float)
    for k, v in CO.items():
        h[k] = v / float(sum(CO.values()))
    return h, sum(CO.values())
Exemple #25
0
def findPeak(array):

    peaks = []
    array.append(0)
    queue = d()
    queue.append(0)

    for item in array:
        if len(queue) < 3:
            queue.append(item)
        if len(queue) == 3:
            if queue[1] >= queue[0] and queue[1] >= queue[2]:
                peaks.append(queue[1])
            queue.popleft()

    return peaks
Exemple #26
0
    def sortByBits(self, arr: List[int]) -> List[int]:
        dic = d(list)

        for i in arr:
            c = 0
            for s in str(bin(i)):
                if s == "1":
                    c += 1
            dic[c].append(i)

        output = []
        for j in range(15):
            if dic[j]:
                for temp in sorted(dic[j]):
                    output.append(temp)

        return output
Exemple #27
0
def e(c):
    global u
    if c == 3:
        q, a, t = d(v), [[0] * m for _ in g(n)], 0
        while q:
            i, j = q.popleft()
            for y, x in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
                if 0 <= y < n and 0 <= x < m and not a[y][x] and not b[y][x]:
                    a[y][x], t = 1, t + 1
                    q.append((y, x))
        u = min(u, t)
        return
    for i in g(n):
        for j in g(m):
            if not b[i][j]:
                b[i][j] = 1
                e(c + 1)
                b[i][j] = 0
Exemple #28
0
 def create_other_lattice(self, density):
     """
     initialize the lattice with a bunch of different types of cells
     (represented as different colors)
     :param density:
     """
     lattice = r(self.x, self.y)
     if density != 1:
         for bug in np.ravel(lattice):
             if r() > density:
                 lattice[lattice == bug] = 0
     # killdict is a hashtable containing the killing effectiveness for each color
     killdict = d(list)  # type: defaultdict[Any, float]
     killdict[0] = 0
     for color in np.ravel(lattice):
         killdict[color] = r()
     killdict[0] = 0
     return lattice, killdict
Exemple #29
0
    def findRotateSteps(self, ring, key):
        from collections import defaultdict as d
        import numpy as np
        dictKey = d()
        for k in key:
            if k in dictKey:  #剔除一样的
                continue
            else:
                dictKey[k] = []
                for j, r in enumerate(ring):
                    if k == r:
                        dictKey[k].append(j)
        print(dictKey)

        lenth = len(ring)
        result = 0

        def updateDict(nums):
            for key in dictKey.keys():
                for i in range(len(dictKey[key])):
                    dictKey[key][i] += nums
                    if dictKey[key][i] < 0:
                        dictKey[key][i] += lenth
                    elif dictKey[key][i] > lenth - 1:
                        dictKey[key][i] -= lenth

        for k in key:
            steps = [(lenth - lc) for lc in dictKey[k]] + dictKey[k]
            minStep = np.min(steps)
            index = steps.index(minStep)
            print("index", index, steps)
            if index < len(dictKey[k]):  #顺时针,注意顺时针转过去是 lenth-取序号
                updateDict(minStep)
                result += minStep
                print('%s:顺时针:%d' % (k, minStep))
            else:  #逆时针
                updateDict(-minStep)
                result += minStep
                print('%s:逆时针:%d' % (k, minStep))
            result += 1
            print(dictKey)

        print(result)
        return result
def graph(state, goal):
    graph = defaultdict(list)
    visited_queue = d()
    visited_queue.append(state)
    while visited_queue:
        state = visited_queue.popleft()
        if left(state) is not None and left(state) not in graph[state]:
            graph[state].append(left(state))
        if right(state) is not None and right(state) not in graph[state]:
            graph[state].append(right(state))
        if up(state) is not None and up(state) not in graph[state]:
            graph[state].append(up(state))
        if down(state) is not None and down(state) not in graph[state]:
            graph[state].append(down(state))
        for curr_state in graph[state]:
            if curr_state not in visited_queue:
                visited_queue.append(curr_state)
                if curr_state == goal:
                    return graph
    return graph
Exemple #31
0
def brainfuck(code,input=input):
    from collections import defaultdict as d
    from ctypes import py_object as p
    hack=lambda v:p.from_address(v)
    l=input==__builtins__.input
    if not l:input=lambda i=1:input.pop(i-1)
    a,o=d(int),''
    i=p=t=0
    gulag = [hack(id(IndexError)).value]
    hack(id(__builtins__.IndexError)).value=StopIteration
    for c in iter(lambda:code[p],None):
        def __0(i,*_):
            a[i]+=1
            a[i]%=256
            return i,*_,
        def __1(i,*_):
            a[i]-=1
            a[i]%=256
            return i,*_,
        def __2(i,o,t):
            o+=chr(a[i])
            return i,o,t
        def __3(i,*_):
            a[i]+=ord(input(1))%256
            return i,*_,
        f = [__0,__1,
             lambda i,*_:(i+1,*_),
             lambda i,*_:(i-1,*_),
             __2,__3,
             lambda i,o,t:(i,o,t+(not a[i])),
             lambda i,o,t:(i,o,t-bool(a[i])),lambda*_:_][chars.find(c)]
        if t:
            if c=='[':t+=1
            if c==']':t-=1
        else:
            i,o,t = f(i,o,t)
        p += 1 - 2*(t<0)
    hack(id(IndexError)).value = gulag.pop(0)
    return o,int(p!=len(code))
def minLevelSum(root):
    # Base case
    if root is None:
        return 0

    # Initialize result
    result = root.val

    q = d()
    q.append(root)

    while q:
        count = len(q)

        # Iterate for all the nodes in the queue currently
        sum = 0
        while count > 0:
            count -= 1

            # Dequeue an node from queue
            temp = q[0]
            q.popleft()

            # Add this node's value to current sum.
            sum += temp.val

            if temp.left is not None:
                q.append(temp.left)

            if temp.right is not None:
                q.append(temp.right)

        # Update the minimum node count value
        result = min(result, sum)

    return result
Exemple #33
0
def parse_gum(gum):
    from collections import defaultdict as d
    start0, end0, start1, end1 = d(list), d(list), d(list), d(list)
    macro = {}
    uid0, uid1 = d(list), d(list)
    cur = {'start': start0, 'end': end0, 'uid': uid0, 'v': '0'}
    for l in gum.splitlines():
        if l == '-----':
            cur = {'start': start1, 'end': end1, 'uid': uid1, 'v': '1'}
            continue
        uid, start, end, action, mid, title, aux = l.split(' ', 6)
        uid, start, end, = int(uid), int(start), int(end)
        if mid != 'NA':
            mid = int(mid)
            cur['start'][start].append('<span id="map-{}-{}"></span>'.format(cur['v'], mid))
        cur['start'][start].append('<span class="{}" id="act-{}" title="{}" data-map="{}">'.format(action, uid, title, mid))
        cur['end'][end].append('</span>')
        if aux != '' and aux != '()':
            macro[uid] = (aux, cur['v'])
        cur['uid'][start].append(uid)
    return start0, end0, start1, end1, macro, uid0, uid1
Exemple #34
0
#!/usr/bin/env python
#By Jai Dhyani
#Automatically generated on 2010-11-14

from collections import defaultdict as d

def get_next(choice):
    return{1 : [2,3,4,5],
           2 : [3,4,5],
           3 : [4,5],
           4 : [5],
           5 : []}[choice]

if __name__ == "__main__":
    envelopes=d(lambda: 0.0, {(2,3,4,5):1.0})
    e_single_paper=0.0
    for i in xrange(13):
        p_round=0.0
        next_envelopes=d(lambda:0.0)
        for envelope,p in envelopes.iteritems():
            for choice in envelope:
                l_env = list(envelope)
                l_env.remove(choice)
                next_papers=tuple(sorted(l_env+get_next(choice)))
                p_next_papers=p*1.0/len(envelope)
                p_round+=p_next_papers
                if len(next_papers)==1:
                    print next_papers, p_next_papers
                    e_single_paper+=p_next_papers
                next_envelopes[next_papers]+=p_next_papers
        envelopes=next_envelopes
Exemple #35
0
from collections import defaultdict as d

if __name__ == '__main__':
    dfd = d(list)
    n, m = [int(i) for i in input().strip().split(" ")]
    for i in range(n):
        dfd[input().strip()].append(i + 1)
    for i in range(m):
        inp = input().strip()
        if dfd[inp]:
            for j in dfd[inp]:
                print(j, end=" ")
            print()
        else:
            print(-1)
Exemple #36
0






def refresh_palette_window():
    a = c["cytron"]["windows"]["palette"]
    a.clear()
    


c = d([
    windows:
    [
	palette:
	[
	    refresh: refresh_palette_window,
	    items: []
	    draw:   draw_palette_window
	]    
    
	editor:
	[
	    files=d([])
	    draw: draw_editor_window
	    
    ]	    
	    
    palette:d("root":"php file", 
			["root","php file"]:["name", "contents"],