[英]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.