Python Minimum Skew函数

时间:2016-10-12 10:44:40

标签: python

我使用以下代码查找MinimumSkew:

genome = "TAAAGACTGCCGAGAGGCCAACACGAGTGCTAGAACGAGGGGCGTAAACGCGGGTCCGAT"

def Skew(genome):    
Skew = {}

Skew[0] = 0
for i in range(1, len(genome)+1):
    if genome[i - 1] == "G":
        Skew[i] = Skew[i - 1] + 1
    elif genome[i - 1] == "C":
        Skew[i] = Skew[i - 1] - 1
    else:
        Skew[i] = Skew[i-1]
return Skew
Skew(genome)


def MinimumSkew(genome):

positions = [] # output variable
s = Skew(genome)
m = min(s.values())
for (k,v) in s.items():
    if v == m:
        positions.append(k)
        return positions
print(MinimumSkew(genome))

我一直收到错误: 测试#5失败。您的代码未找到所有最小偏差索引。

测试数据集: CCGGCCGG

你的输出: [11] 2

正确输出: 2 6 任何人都可以帮我解决我做错的事吗?

1 个答案:

答案 0 :(得分:0)

计算偏差有更简单的解决方案。这是一种方法:

def skew(genome):
    res = []
    cntr = 0
    res.append(cntr)
    for i in genome:
        if i == 'C':
            cntr -= 1
        if i == "G":
            cntr += 1
        res.append(cntr)
    return [str(i) for i, j in enumerate(res) if j == min(res)]

print(skew('CCGGCCGG')) # returns ['2', '6']

你的解决方案也很好,你只需要修复缩进:

genome = "CCGGCCGG"

def Skew(genome):
    Skew = {}

    Skew[0] = 0
    for i in range(1, len(genome)+1):
        if genome[i - 1] == "G":
            Skew[i] = Skew[i - 1] + 1
        elif genome[i - 1] == "C":
            Skew[i] = Skew[i - 1] - 1
        else:
            Skew[i] = Skew[i-1]
    return Skew


def MinimumSkew(genome):

    positions = [] # output variable
    s = Skew(genome)
    m = min(s.values())
    for (k,v) in s.items():
        if v == m:
            positions.append(k)
    return positions
print(MinimumSkew(genome))

这会返回[2, 6]