我是一個Python和堆棧溢出新手。Codingbat:Warmup- last2在線編譯器顯示編譯錯誤,即使它在交互式shell中完美工作
以下是問題的聲明http://codingbat.com/prob/p145834
Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).
Expected Outputs: last2('hixxhi') → 1 last2('xaxxaxaxx') → 1 last2('axxxaaxx') → 2
以下是我的代碼:
def last2(str):
flag=0
count=0
ss=str[-2]+str[-1]
for i in range(0,len(str)-1,1):
flag=1
for j in range(0,2,1):
if ss[j]!=str[i+j]:
flag=0
break
if(flag==1):
count=count+1
return count-1
解釋代碼: 的代碼是基於標準算法用於搜索字符串中的子字符串。這裏ss代表接收字符串str的最後兩個字符的子字符串。在字符串中搜索子字符串,count存儲重複次數。由於我們不希望最後兩個字符根據問題陳述被視爲重複,因此返回值count-1。
這對脫機交互式shell(使用python 3.5)非常有效。
但網上的編譯器/解釋器顯示了相同的代碼以下錯誤信息:
Compile problems:
Error:string index out of range
(截圖,不是因爲低於10的聲譽封閉的,因爲我是新手)
錯誤的原因是什麼?
標籤'編譯器錯誤'是誤導,因爲這顯然是一個運行時錯誤。 – BlackJack
我將刪除該標籤。 –