2015-12-10 30 views
3

我是一個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)非常有效。

Screenshot enclosed

但網上的編譯器/解釋器顯示了相同的代碼以下錯誤信息:

Compile problems:

Error:string index out of range

(截圖,不是因爲低於10的聲譽封閉的,因爲我是新手)

錯誤的原因是什麼?

+0

標籤'編譯器錯誤'是誤導,因爲這顯然是一個運行時錯誤。 – BlackJack

+0

我將刪除該標籤。 –

回答

2

當您在翻譯中嘗試使用 last2("")時會發生什麼?

我認爲這是你的問題所在。

但是,這個問題並沒有說明如何處理長度爲< 2的字符串,所以它有點讓你期待你處理它。

我做了一個很好的快速解決方案,但我會讓你找到它自己的解決方案,除非你想要更多的幫助。

+1

非常感謝!你是對的:我錯過了測試用例last2('')。我只需添加一個if條件來將len(str)<2考慮進去。 –

+2

你的解決方案似乎相當「健談」。 :-) def last2(string): s = string [-2:]; return sum(string [i:i + 2] == s爲我在範圍內(len(字符串))) - bool(s) – BlackJack

+0

工作!終於明白了。謝謝你。有沒有什麼資源可以推薦進一步學習Python?我目前使用這個:https://automatetheboringstuff.com/ –