2016-09-10 8 views
-1

私はExを解決しようとしています。私のアプローチは、1ずつ率を高めることにより、数値に文字を変換し、単語の次の文字でそれらを一致させることですPythonで "IndexError:string index of range"をデバッグするには?

fin= open('words.txt') 
for line in fin: 
line=fin.readline() 
word=line.strip() 
c=0 
index=0 
for letter in word: 
    if ord(letter)<ord(word[index+1]): 
     c=c+1 
     index=index+1 
if c==len(word): 
    print(word) 

:9.6 Pythonの3.私が書いた何

Question: Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there?

を考えます時間ループは終了し、毎回カウントされます。 countが単語の長さと等しくなると、以前の文字は次の文字よりも価値が低いということです。それで言葉を印刷してください。

エラー:

Traceback (most recent call last): File "C:\Users\KARAN\Desktop\Python\Programs\practice.py", line 8, in <module> if ord(letter)<ord(word[index+1]): IndexError: string index out of range 

私は 'はIndexError' を取得していますが、私は0 + 1 = 1であるインデックスが範囲外であるべきだと思いませんか?私はそれを検索しようとしましたが、私の答えを得ることができませんでした。

+1

エラーの**フル**トレースバックを含めてください。どのような状況で、どのような状況で推測されているのか推測しておかないでください。 –

+1

Pythonインデックスは0から始まり、 'len(sequence) - 1'で終わります。ここで 'len(word)'までループしているので、最後の文字のインデックスエラーが出ます。 –

+0

ああ..ありがとうMartijn、私はそれを世話しませんでした。 Lemmeはこれでもう一度試してください – Vito

答えて

1

(OPのために掲示される)

最終的な解決策:

fin= open('words.txt') 
for line in fin: 
    line=fin.readline() 
    word=line.strip() 
    c=0 
    index=0 
    while index!=(len(word)-1): 
     i=(word[index]) 
     j=(word[index+1]) 
     index=index+1 
     if ord(j)>=ord(i): 
      c=c+1 
    if c==(len(word)-1): 
     print(word) 
+1

私は、あなたが何も漏れていないことを確認するために 'fin.close()'を行う必要があることに言及する価値があると思います。単純な 'with open( 'words.txt)as fin:'ブロックはそれを処理します。 – Minato

+0

私は確かに感謝の男を追加します – Vito

関連する問題