2016-09-11 253 views
1

我不斷收到IndexError: string index out of range異常在下面的代碼,我不明白爲什麼。IndexError:字符串索引超出範圍?

我應該遞歸解決以下問題。

Finally, write transcribe(S) . Here is its description:

In an incredible molecular feat called transcription, your cells create molecules of messenger RNA that mirror the sequence of nucleotides in your DNA. The RNA is then used to create proteins that do the work of the cell. Write a recursive function transcribe(S) , which should take as input a string S , which will have DNA nucleotides (capital letter As, Cs, Gs, and Ts). There may be other characters, too, though they will be ignored by your transcribe function—these might be spaces or other characters that are not really DNA nucleotides.

Then, transcribe should return as output the messenger RNA that would be produced from that string S. The correct output simply uses replacement:

As in the input become Us in the output.
Cs in the input become Gs in the output.
Gs in the input become Cs in the output.
Ts in the input become As in the output.
any other input characters should disappear from the output altogether

def transcribe(S): 
    tran = '' * len(S) 
    if S[0] == 'A': 
    tran = tran + 'U' + transcribe(S[1:]) 
    return tran 
    elif S[0] == 'C': 
    tran = tran + 'G' + transcribe(S[1:]) 
    return tran 
    elif S[0] == 'G': 
    tran = tran + 'C' + transcribe(S[1:]) 
    return tran 
    elif S[0] == 'T': 
    tran = tran + 'A' + transcribe(S[1:]) 
    return tran 
    else: 
    return "" 

print transcribe('GATTACA') 

回答

3

試圖指數隨[0]空字符串引發IndexError

您需要測試,如果字符串爲空第一,作爲最終S[1:]將傳遞一個空蜇到transcribe()

if not S: 
    return '' 

你應該完全放棄的tran串;即總是一個空字符串。 '' * <any number>仍然是''

,而不是一個單獨的if語句來測試每個可能的字母,使用字典映射一個角色到另一個:

mapping = {'A': 'U', 'C': 'G', 'G': 'C', 'T': 'A'} 
def transcribe(S): 
    if not S: 
     return '' 
    replacement = mapping.get(S[0], '') # default is empty 
    return replacement + transcribe(S[1:]) 
+0

這工作!我不知道我是如何錯過的。非常感謝!! –

0

這裏的東西有點接近原來的:

def transcribe(S): 
    if S == '': 
     return '' 
    elif S[0] == 'A': 
     return 'U' + transcribe(S[1:]) 
    elif S[0] == 'C': 
     return 'G' + transcribe(S[1:]) 
    elif S[0] == 'G': 
     return 'C' + transcribe(S[1:]) 
    elif S[0] == 'T': 
     return 'A' + transcribe(S[1:]) 
    else: 
     return transcribe(S[1:]) 

print transcribe('GATTACA') 
相關問題