List Comprehension Showing IndexError - python

I'm creating a hangman game. I came up with an idea to replace underscores with a letter. First the user inputs their guess (the letter "c" in this case). I search through a list containing the letters of the unknown word creating a list with the indices of each time there is a hit for that letter. Then I search through the list of underscores and replace all the underscores with the letter using the index list I created. However, I'm getting an error:
IndexError: list index out of range.
What am I doing wrong in the below code?
y = "cctcc"
to_modify = ["_", "_", "_","_", "_"]
replacements = list(y)
user_input = input()
indexes = [i for i, j in enumerate(replacements) if j == user_input]
print(indexes)
for index in indexes:
to_modify[indexes[index]] = replacements[index]
print(to_modify)
Output:
[0, 1, 3, 4]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-25-be2b07a156e5> in <module>()
10 print(indexes)
11 for index in indexes:
---> 12 to_modify[indexes[index]] = replacements[index]
13
14 print(to_modify)
IndexError: list index out of range

This section of the code is already looping over the indices:
for index in indexes:
to_modify[indexes[index]] = replacements[index]
If indexes contains [0,1,3,4], when index loops to 4 it's trying to access indexes[4] which is out of range, just use the indexes you're getting from the loop:
for index in indexes:
to_modify[index] = replacements[index]

Related

Python, index out of range, list

I need to change the number with the highest index and the number with the lowest index between each other in the entered line, but an error pops out
Error:
list2[0], list2[len1] = list2[len1], list2[0]
IndexError: list index out of range
Code:
list1 = input("Введите список: ")
list2 = list1.split()
len1 = int(len(list2))
list2[0], list2[len1] = list2[len1], list2[0]
print(list2)
How can this be fixed?
Use index [-1] instead of len(list2)-1 to get the last element:
list1 = input("Введите список: ").split()
list1[0], list1[-1] = list1[-1], list1[0]
print(list1)
List are indexing from 0. If your list contains 4 elements, the length is 4 but the last index is 3 (4 - 1).
list1 = input("Введите список: ")
list2 = list1.split()
len1 = int(len(list2)) - 1 # <- HERE
list2[0], list2[len1] = list2[len1], list2[0]
print(list2)
The indexing is always 0 - length-1.
So if you take the list value at length, it will be out of the aforementioned index range.
Another thing I would like to point out is that your variable names are really very confusing. It's a small code, however for bigger projects, when you'll have to debug this, it will be a serious pain for you.
However, this should work
ip = input("Введите список: ")
list1 = ip.split(" ")
len1 = int(len(list1))
list1[0], list1[len1-1] = list1[len1-1], list1[0]
print(list1)
As the Error states, the index for the "list2[len1]" is out of range.
Since len() method in python returns the actual length of the list, whereas the indexing of list starts with 0th position
for the above code, you can try doing this:
list2[0], list2[len1-1] = list2[len1-1], list2[0]

How do i print only (bottem) part of a dictionary in python3?

I have created a dictionary by counting a list of positives words(positives.txt) over a list of tweets(tweets.txt).
Now im trying to print the top 5 used postitive words with respective scores.
I have managed to sort the scores and able to print the whole list of words with their scores, like:
(rest of list...)
wordx 5
wordy 28
wordz 35
My goal is to print (just) a top 3:
wordz 35
wordy 28
wordx 5
I tried giving indexes en subscripts at different places but keep getting error messages like:
Traceback (most recent call last):
print(word[3], score[3])
IndexError: string index out of range
print(word[0:5], score[0:5])
TypeError: 'int' object is not subscriptable
Current Code:
def positive_word(tweets, positives):
"""prints the top 5 most used positive words"""
x = {}
#for l in range(5):
for l in range(len(positives)):
x[positives[l]] = 0
#for m in range (5):
for m in range (len(tweets)):
#for n in range (5):
for n in range (len(positives)):
if positives[n] in tweets[m]:
x[positives[n]] += 1
for word, score in sorted(x.items(), key = lambda key : key[1]):
print(word, score)

How to fix my code's error "List index out of range"

How do I fix the error my code comes up with the following?
Traceback (most recent call last):
File "main.py", line 143, in <module>
print(question_list2[random_int])
IndexError: list index out of range
This is the code in question:
question_list2 = []
question_list2.append(" the marines are ___ based opreatives ")
question_list2.append(" for under water travel marines use _____ ")
question_list2.append(" the avergae marine trains for _ weeks ")
answer_list2 = []
answer_list2.append("sea")
answer_list2.append("subamrines")
answer_list2.append("13")
top_index = 4
correct = 0
for i in range (0,4):
random_int = random.randint(0,top_index)
print(question_list2[random_int])
top_index = top_index - 1
user_answer1 = input("fill in the blank with the correct word ")
if user_answer == answer_list1[random_int]:
correct = correct + 3
del question_list1[random_int]
del answer_list1[random_int]
From the random docs
random.randint(a, b)
Return a random integer N such that a <= N <= b
This means that:
top_index = 4
random_int = random.randint(0,top_index)
Has the possibility of setting random_int to 3 or 4 which are outside the range of your list which only has three items with index 0, 1, and 2.
Rather than mutating your lists and using indexes, it might be easier to make a list of indexes, shuffle it, then iterate over it:
indexes = random.sample(range(0, len(question_list)), k = len(question_list))
for i in indexes:
# etc...
If you kept the questions and answers together in a single list, you could do away with the indexes altogether. This would be a good use for named tuples
import random
from collections import namedtuple
qa = namedtuple('QA', ['question', 'answer'])
question_list = [
qa(" the marines are ___ based opreatives ", 'sea'),
qa(" for under water travel marines use _____ ",'submarines'),
qa(" the avergae marine trains for _ weeks ", '13')
]
random.shuffle(question_list)
correct = 0
for qa in question_list:
print(qa.question)
user_answer = input("fill in the blank with the correct word ")
if user_answer == qa.answer:
correct = correct + 1
I believe that you only have three things on your list. The range should be range(0,3) and maybe your top_index should be top_index = 2.
Since the indexes on your list are [0,1,2]
The first item in list > index = 0
The second item in list > index = 1
The third item in list > index = 2

TypeError list indices must be integers

I have recently started to learn python. The following code is throwing type error stating that I can't use tuples as index in a list. I am quite sure I am using integers and not list to access to access my list. The error is thrown at the line where I build a sub-matrix. Can you help me out?
Traceback (most recent call last):
File "matrix_input.py", line 44, in <module>
print(contains(matrix, target))
File "matrix_input.py", line 33, in contains
sub_matrix = [row[index:len(target[0])] for row in matrix[i, len(target)]]
TypeError: list indices must be integers, not tuple
This is the function throwing the error:
def sub_array(row, sub_row):
i = 0
index = -1
for idx, val in enumerate(row):
if i >= len(sub_row):
break
elif val == sub_row[i]:
index = idx
i+=1
else:
i = 0
return index if i == len(sub_row) else -1
def contains(matrix, target):
for i in range(len(matrix)):
index = sub_array(matrix[i], target[0])
if index is not -1:
sub_matrix = [row[index:len(target[0])] for row in matrix[i, len(target)]]
print(sub_matrix)
if sub_matrix == target:
return "YES"
return "NO"
matrix[i, len(target)] attempts to access an item in matrix with the tuple i, len(target) as an index – not an integer. It appears you intended to use matrix[i][len(target)] instead.
You should compare integers with ==/!=, too – index != -1 instead of index is not -1.

String Index Out of Range Error in Python

I keep getting an "IndexError: string index out of range" error message when I try to execute this code:
#function countLetters(word,letter) should count the number of times
#a particular letter appears in a word.
def countLetters(word, letter):
count=0
wordlen=len(word)
num=0
wordletter=""
while(num<=wordlen):
wordletter=word[num]
if(wordletter==letter):
count=count+1
num=num+1
return count
print(countLetters("banana", "x"))#should print 0
print(countLetters("banana", "a"))#should print 3
print(countLetters("banana", "b"))#should print 1
The Error Message:
Traceback (most recent call last):
File "C:\Users\Charlie Chiang\Desktop\9G.py", line 17, in <module>
print(countLetters("banana", "x"))
File "C:\Users\Charlie Chiang\Desktop\9G.py", line 10, in countLetters
var=word[num]
IndexError: string index out of range
You take it one index too far:
while(num<=wordlen):
num must stay strictly below the length:
while num < wordlen:
because Python sequences are 0-based. A string of length 5 has indices 0, 1, 2, 3, and 4, not 5.
You are reaching one index too far:
while(num<=wordlen):
For a text "a" the len("a") is 1 and last letter can be reached by index 0. Your while condition allows trying index 1, which is not available.
Bonus: counting using Counter
Python stdlib collections provides excellent Counter:
>>> from collections import Counter
>>> Counter("banana").get("x", 0)
0
>>> Counter("banana").get("a", 0)
3
Fixing your code:
def countLetters(word, letter):
count=0
wordlen=len(word)
num=0
wordletter=""
#here, because the index access is 0-based
#you have to test if the num is less than, not less than or equal to length
#last index == len(word) -1
while(num<wordlen):
wordletter=word[num]
if(wordletter==letter):
count=count+1
num=num+1
return count
print(countLetters("banana", "x"))#should print 0
print(countLetters("banana", "a"))#should print 3
print(countLetters("banana", "b"))#should print 1
more elegant way:
str.count method
'banana'.count('x')
'banana'.count('a')
'banana'.count('b')
Because the index of the string starts at zero, the highest valid index will be wordlen-1.
The index start at 0, not 1.
Try changing:
wordletter = word[num-1]

Categories

Resources