コード例 #1
0
    def openLock(self, deadends, target):
        """
        :type deadends: List[str]
        :type target: str
        :rtype: int
        """
        dead_set = set(deadends)
        queue = Collection.deque([("0000", 0)])
        visited = set("0000")

        while queue:
            (string, steps) = queue.popleft()
            if string == target:
                return steps
            elif string in dead_set:
                continue
            for i in range(4):
                digit = int(string[i])
                for move in [-1, 1]:
                    new_digit = (digit + move) % 10
                    new_string = string[:i] + str(new_digit) + string[i + 1 :]
                    if new_string not in visited:
                        visited.add(new_string)
                        queue.append((new_string, steps + 1))
        return -1
コード例 #2
0
    def findLadders(self, beginWord, endWord, wordList):

        wordList = set(wordList)
        res = []
        layer = {}
        layer[beginWord] = [[beginWord]]

        while layer:
            newlayer = Collection.defaultdict(list)
            for w in layer:
                if w == endWord:
                    res.extend(k for k in layer[w])
                else:
                    for i in range(len(w)):
                        for c in "abcdefghijklmnopqrstuvwxyz":
                            neww = w[:i] + c + w[i + 1:]
                            if neww in wordList:
                                newlayer[neww] += [
                                    j + [neww] for j in layer[w]
                                ]

            wordList -= set(newlayer.keys())
            layer = newlayer

        return res
コード例 #3
0
 def canReorderDoubled(self, A):
     c = Collection.Counter(A)
     for x in sorted(c, key=abs):
         if c[x] > c[2 * x]:
             return False
         c[2 * x] -= c[x]
     return True
コード例 #4
0
 def numMatchingSubseq(self, S, words):
     waiting = Collection.defaultdict(list)
     for it in map(iter, words):
         waiting[next(it)].append(it)
     for c in S:
         for it in waiting.pop(c, ()):
             waiting[next(it, None)].append(it)
     return len(waiting[None])
コード例 #5
0
 def customSortString(self, S: str, T: str) -> str:
     ans, cnt = [], Collection.Counter(T)  # count each char in T.
     for c in S:
         if cnt[c]:
             ans.extend(
                 c * cnt.pop(c)
             )  # sort chars both in T and S by the order of S.
     for c, v in cnt.items():
         ans.extend(c * v)  # group chars in T but not in S.
     return "".join(ans)
コード例 #6
0
 def distributeCandies(self, candyType: List[int]) -> int:
     n, cnt = len(candyType), 0
     table = Collection.defaultdict(int)
     for i in candyType:
         if cnt >= n / 2:
             break
         if table.get(i) is None:
             table[i] += 1
             cnt += 1
     return table.__len__()
コード例 #7
0
 def findDuplicate(self, paths):
     """
     :type paths: List[str]
     :rtype: List[List[str]]
     """
     map = Collection.defaultdict(list)
     for line in paths:
         data = line.split()
         root = data[0]
         for file in data[1:]:
             name, _, content = file.partition('(')
             map[content[:-1]].append(root + '/' + name)
     return [x for x in map.values if len(x) > 1]
コード例 #8
0
def check_collections_equivalent(
        a: typing.Collection,
        b: typing.Collection,
        allow_duplicates: bool = False,
        element_converter: typing.Callable = identity
) -> typing.Tuple[str, list]:
    """

    :param a: one collection to compare
    :param b: other collection to compare
    :param allow_duplicates: allow collections to contain multiple elements
    :param element_converter: optional function to convert elements of collections to a different value
                              for comparison
    :return: (message, differences)
    """
    a = Counter(map(element_converter, a))
    b = Counter(map(element_converter, b))
    if not allow_duplicates:
        duplicates = []
        for name, counts in [['a', a], ['b', b]]:
            for key, count in counts.items():
                if count > 1:
                    duplicates.append([name, key, count])
        if duplicates:
            return 'Duplicate elements ', [
                '|'.join(map(str, dup)) for dup in duplicates
            ]

    diffs = []
    for el in a | b:
        ac = a.get(el, 0)
        bc = b.get(el, 0)
        if ac != bc:
            'Inconsistent element frequencies', diffs.append(
                f'{el} a={ac} b={bc}')
    if diffs:
        return "Inconsistent element frequencies: ", diffs

    return 'Collections equivalent', []
コード例 #9
0
 def minWindow(self, s, t):
     need, missing = Collection.Counter(t), len(t)
     i = I = J = 0
     for j, c in enumerate(s, 1):
         missing -= need[c] > 0
         need[c] -= 1
         if not missing:
             while i < j and need[s[i]] < 0:
                 need[s[i]] += 1
                 i += 1
             if not J or j - i <= J - I:
                 I, J = i, j
     return s[I:J]
コード例 #10
0
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        gcd = 0
        # Find frequency of each card number
        freq = Collection.Counter(deck)

        # Calculate GCD of freq dictionary 
        for (key, value) in freq.items():
            if gcd == 0:
                gcd = value
            else:
                gcd = math.gcd(gcd, value)

        if gcd == 1:
            return False
        return True
 def minReorder(self, n: int, connections: List[List[int]]) -> int:
     a2b, b2a = Collection.defaultdict(set), collections.defaultdict(set)
     for i, j in connections:
         a2b[i].add(j)
         b2a[j].add(i)
     s = [0]
     seen = set(s)
     cnt = 0
     while s:
         city = s.pop()
         for nxt in b2a[city] | a2b[city]:
             if nxt not in seen:
                 cnt += nxt in a2b[city]
                 seen.add(nxt)
                 s.append(nxt)
     return cnt
コード例 #12
0
 def reachableNodes(self, edges, M, N):
     e = Collection.defaultdict(dict)
     for i, j, l in edges:
         e[i][j] = e[j][i] = l
     pq = [(-M, 0)]
     seen = {}
     while pq:
         moves, i = heapq.heappop(pq)
         if i not in seen:
             seen[i] = -moves
             for j in e[i]:
                 moves2 = -moves - e[i][j] - 1
                 if j not in seen and moves2 >= 0:
                     heapq.heappush(pq, (-moves2, j))
     res = len(seen)
     for i, j, k in edges:
         res += min(seen.get(i, 0) + seen.get(j, 0), e[i][j])
     return res
コード例 #13
0
ファイル: base.py プロジェクト: kantholtz/pykeen
    def to_embeddingdb(self, session=None, use_tqdm: bool = False):
        """Upload to the embedding database.

        :param session: Optional SQLAlchemy session
        :param use_tqdm: Use :mod:`tqdm` progress bar?
        :rtype: embeddingdb.sql.models.Collection
        """
        from embeddingdb.sql.models import Embedding, Collection

        if session is None:
            from embeddingdb.sql.models import get_session
            session = get_session()

        collection = Collection(
            package_name='pykeen',
            package_version=get_version(),
            dimensions=self.embedding_dim,
        )

        embeddings = self.entity_embeddings.weight.detach().cpu().numpy()
        names = sorted(
            self.triples_factory.entity_to_id,
            key=self.triples_factory.entity_to_id.get,
        )

        if use_tqdm:
            names = tqdm(names, desc='Building SQLAlchemy models')
        for name, embedding in zip(names, embeddings):
            embedding = Embedding(
                collection=collection,
                curie=name,
                vector=list(embedding),
            )
            session.add(embedding)
        session.add(collection)
        session.commit()
        return collection
コード例 #14
0
    def sumOfDistancesInTree(self, N, edges):
        tree = Collection.defaultdict(set)
        res = [0] * N
        count = [1] * N
        for i, j in edges:
            tree[i].add(j)
            tree[j].add(i)

        def dfs(root, pre):
            for i in tree[root]:
                if i != pre:
                    dfs(i, root)
                    count[root] += count[i]
                    res[root] += res[i] + count[i]

        def dfs2(root, pre):
            for i in tree[root]:
                if i != pre:
                    res[i] = res[root] - count[i] + N - count[i]
                    dfs2(i, root)

        dfs(0, -1)
        dfs2(0, -1)
        return res
コード例 #15
0
 def __init__(self):
     self.records = Collection.defaultdict(list)
コード例 #16
0
# 1.需要枚举与第一个 ( 对应的 ) 的位置 2 * i + 1;
# 2.递归调用 generate(i) 即可计算 a 的所有可能性;// a 为括号对数为i的括号组合
# 3.递归调用 generate(n - i - 1) 即可计算 b 的所有可能性; // b 为括号对数为n - i - 1的括号组合,减去1是因为第一对括号已存在
# 4.遍历 a 与 b 的所有可能性并拼接,即可得到所有长度为 2 * n 的括号序列。

# 为了节省计算时间,在每次 generate(i) 函数返回之前,把返回值存储起来,下次再调用 generate(i) 时可以直接返回,不需要再递归计算。

# DP 最核心的两点:
# 1.找到递推公式
# 2.缓存结果,避免重复计算
public List<String> generateParenthesis(int n) {
    // 存放缓存信息
    List<List<String>> cache = new ArrayList<>();

    // 初始化第一个元素列表为[""]
    cache.add(Collection.singletonList(""));
    // singletonList(T) 方法用于返回一个只包含指定对象的不可变列表

    for (int i = 1; i <= n; i++) {
        List<String> cur = new ArrayList<>();
        for (int j = 0; j < i; j++) {
            List<String> str1 = cache.get(j); // 计算 a 的所有可能性
            List<String> str2 = cache.get(i - j - 1); // 计算 b 的所有可能性
            for (String s1 : str1) {
                for (String s2 : str2) {
                    // 枚举右括号的位置
                    cur.add("(" + s1 + ")" + s2);
                }
            }
            cache.add(cur);
        }
コード例 #17
0
            if letter not in current:
                return -1
            current = current[letter]
        if self.endSymbol in current:
            return current[self.suffixIndex]


# Your WordFilter object will be instantiated and called as such:
# obj = WordFilter(words)
# param_1 = obj.f(prefix,suffix)

########################################
# THIS IS THE MOST EFFICIENT SOLUTION
########################################

Trie = lambda: Collection.defaultdict(Trie)
WEIGHT = False


class WordFilter(object):
    def __init__(self, words):
        self.trie = Trie()

        for weight, word in enumerate(words):
            word += '#'
            for i in range(len(word)):
                cur = self.trie
                cur[WEIGHT] = weight
                for j in range(i, 2 * len(word) - 1):
                    cur = cur[word[j % len(word)]]
                    cur[WEIGHT] = weight
コード例 #18
0
 def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
     start = end = left = 0
     need = Collection.Counter(t)
コード例 #19
0
from typing import Collection
import pymongo as go
client = go.MongoClient(
    "mongodb+srv://yash:[email protected]/myFirstDatabase?retryWrites=true&w=majority"
)
print(client.list_database_names())
db1 = client["jadoo"]
print(client.list_database_names())
Collection = db1["test"]
record = {"jhdj": "jkdjf", "jdkff": "dfjkf"}
Collection.insert_one(record)
コード例 #20
0
 def maxNumberOfBalloons(self, text: str) -> int:
     cnt = Collection.Counter(text)
     cntBalloon = collections.Counter("balloon")
     return min([cnt[c] // cntBalloon[c] for c in cntBalloon])