我不斷收到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 stringS
, 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')
這工作!我不知道我是如何錯過的。非常感謝!! –