algorithm - 为什么这段代码占用这么多内存?

标签 algorithm python optimization

我为 this 创建了一个解决方案leetcode 问题:

All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.

Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.

我的解决方案导致内存不足异常:

class Solution:
    # @param {string} s
    # @return {string[]}
    def findRepeatedDnaSequences(self, s):
        seen_so_far = set()
        results = set()
        for seq in self.window(10, s):
            if seq in seen_so_far:
                results.add(seq)
            else:
                seen_so_far.add(seq)
        return list(results)

    def window(self, window_size, array):
        window_start = 0
        window_end = window_size
        while window_end < len(array):
            yield array[window_start:window_end+1]
            window_end += window_size

此解决方案有效:

class Solution:
    # @param {string} s
    # @return {string[]}
    def findRepeatedDnaSequences(self, s):
        d = {}
        res = []
        for i in range(len(s)):
            key = s[i:i+10]
            if key not in d:
                d[key] = 1
            else:
                d[key] += 1

        for e in d:
            if d[e] > 1:
                res.append(e)

        return res

它们看起来本质上是一样的。我错过了什么?

最佳答案

您的 window 功能不正确。它产生一个子字符串序列 [0:11], [0:21], [0:31], ...(注意window_start 保持为零)。它可以被修复,例如作为

def window(self, window_size, array):
    window_start = 0
    while window_start < len(array) - window_size + 1:
        yield array[window_start:window_start+window_size]
        window_start += 1

编辑:子字符串结尾索引偏移 1。

关于algorithm - 为什么这段代码占用这么多内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109694/

相关文章:

algorithm - 对 "Exact Algorithm"的定义感到困惑

algorithm - 给定一个整数 z<=10^100,找到包含 z 的帕斯卡三角形的最小行

python - 如何创建颜色和标记的图例?

Python 3.6 合并字典失败

python - 在剧本中使用authorized_key模块为新用户设置SSH key

optimization - Julia 相当于 python Continuous_groups() 函数

algorithm - 删除导致无向图中循环的边

python - 跨多个单词的最小 Levenshtein 距离

algorithm - 在忽略背景的情况下生成对象的直方图

sql - 随机页面成本和计划