繁体   English   中英

我对该功能有什么错?

[英]What did I do wrong with this function?

我不知道自己做了什么-是错的。 有人能帮我吗?

def insert_sequence(dna1, dna2, number):

    '''(str, str, int) -> str
    Return the DNA sequence obtained by inserting the second DNA sequence
    at the given index. (You can assume that the index is valid.)  

    >>> insert_sequence('CCGG', 'AT', 2)
    'CCATGG'
    >>> insert_sequence('TTGC', 'GG', 2)
    'TTGGGC'
    '''
    index = 0
    result = '';
    for string in dna1:
        if index == number:
            result = result + dna2

            result = result + string
            index += 1

            print(result)

这是一个解决方案:

def insert_sequence(dna1, dna2, number):

    '''(str, str, int) -> str
    Return the DNA sequence obtained by inserting the second DNA sequence
    at the given index. (You can assume that the index is valid.)  

    >>> insert_sequence('CCGG', 'AT', 2)
    'CCATGG'
    >>> insert_sequence('TTGC', 'GG', 2)
    'TTGGGC'
    '''

    return dna1[:number] + dna2 + dna1[number:]

您需要在此处执行if-else循环:

def insert_sequence(dna1, dna2, number):


    result = '';

    #you can use enumerate() to keep track of index you're on

    for ind,x in enumerate(dna1): 
        if ind == number:            #if index is equal to number then do this
            result = result + dna2 +x
        else:                        #otherwise do this   
            result = result + x 


    print(result)

insert_sequence('CCGG', 'AT', 2)
insert_sequence('TTGC', 'GG', 2)

输出:

CCATGG
TTGGGC

其他答案中已经有正确的工作功能(特别是Rakesh Pandit的评论和JeffS的答案),但是您的实际问题是“为什么我的原始功能不起作用”。

我复制了您的函数的工作版本,注释如下:

def insert_sequence(dna1, dna2, number):

    index = 0
    result = ''

    for character in dna1:
        if index == number:
            result = result + dna2
        result = result + character
        index += 1
    print(result)

Python考虑缩进,因此您应该只在结尾处,循环外和ifs处打印。 当“增加”结果时,只能在函数的“ if”内部执行此操作,而实际上应增加“针对dna1中的每个字符”,仅当/“ if index == number”时,才应放在中间里面的字符串。

我相信您可能是生物学背景的人,但对Python或一般编程来说还是一个新手,但是您真的不应该像其他人那样反复进行这种类型的字符串操作。

希望这可以帮助!

您永远不会将字符串分开,因此您将始终在dna2之前添加dna1。

您可能要return dna1[:number] + dna2 + dna1[number:]

如果索引不在插入点,则不执行任何操作,包括增加索引。 您的代码需要一个else,并且您还会过早打印:

def insert_sequence(dna1, dna2, number):
    index = 0
    result = '';
    for char in dna1:
        if index == number:
            result = result + dna2
            result = result + char
            index += len(dna2) + 1
        else:
            result = result + char
            index += 1
    print(result)

犯了错误:a)参数索引初始化为0。b)“对于dia1中的字符串:”应该为“对于range(len(dia1))中的dia1_position:” c)打印结果缩进错误,并且功能不只是应该打印。 它应该返回结果。 d)索引现在不需要增加。

答案已经在那里。 上面简要列出了所犯的错误。 我猜您没有看到任何错误,因为您从未调用过该函数。 第一个错误应该是未定义的“数字”(由于问题已更新且参数已定义数字,因此不再错误)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM