user4624958
user4624958

Reputation:

Python "list index out of range" error in list iteration

What am I doing Wrong? "list index out of range" on line 7 Sorry for russian letters in code, it's my hometask. Help me please.

import sys
morze = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.']
ralphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' #Russian alphabet 0-32
doc = "Вот цитата для тебя : Встретив двусмысленность , отбрось искушение угадать . С наилучшими пожеланиями , Андрей ." #doc = open('text.txt') 
print('Не поддерживается правильное отображение знаков препинания. Ставьте знаки через пробел.') #Attention
for line in doc:
    line = line.lower() #Downcase
    for word in line.split(' '):
        ln = len(word) #Length of word
        if ln == 1 and word in ralphabet: #One-letter words
            letternumber = ralphabet.find(word)
            sys.stdout.write(morze[letternumber] + ' ')
        elif ln == 1: #Symbols
            ...
        elif ln != 1 and not (word[0] in alphabet): #Symbols error
            sys.stdout.write('[ERROR]')
        elif ln != 1: #Long words
            shift = ln - 1
            if shift > 10:
                shift = 10
            for letter in word:
                letternumber = ralphabet.find(letter) + 1 - shift
                for digit in str(letternumber):
                    sys.stdout.write(morze[digit] + ' ')
            sys.stdout.write('| ')
        sys.stdout.write('| ')

input() #PAUSE

Upvotes: 0

Views: 95

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You are using the index of the word to find something in the morze list if you print(letternumber,len(morze)) you can see exactly why you get the error:

  (31, 10)
   ^    ^   

The length of ralphabet is 66 and the length of morze is 10 so that is not going to work.

You might also want to change these two lines:

 elif ln > 1 and word[0] not in alphabet:  #Symbols error
            sys.stdout.write('[ERROR]')
 elif ln > 1:  #Long words

0 is also != 1 but word[0] is not going to work .

You are also calling str on letternumber then trying to pass a string as an index:

       for digit in str(letternumber):
             sys.stdout.write(morze[digit] + ' ')
                                       ^
                                       string = error

You could use:

  for digit in range(letternumber):
         sys.stdout.write(morze[digit] + ' ')

But again if letternumber = ralphabet.find(letter) + 1 - shift is greater than 10 you would get an error.

Upvotes: 1

Related Questions