andy399
andy399

Reputation: 35

How to fix an IndexError Problem for printing words from a list

For my beginning python class we have to write a code that determines if a number is prime, finds the average word length in a sentence, determines which words in a sentence have prime lengths, and then prints the words that have prime lengths. (we don't need to worry about punctuation for this assignment) So I've written the following code, but when I try to print the words that have prime lengths it's returning list index out of range The code works fine through the first for loop, and returns True for however many prime lengths are entered, but I can't get it to print the actual words. Please help!

from statistics import mean


def is_prime(n):
    if n < 2:
        return(False)
    else:
        for i in range(2, n + 1):
            if n == 2:
                return(True)
                break
            elif n % i == 0:
                return(False)
                break
            else:
                return(True) 
                break   
    return


user_input = " "
while user_input != "quit":
    user_input = input("Please enter a random sentence (or type 'quit' to exit): ")
    word_list = user_input.split()
    x = len(word_list)
    word_length = []

    for i in range(x):
        word_length.append(len(word_list[i]))


    for i in word_length:
        if is_prime(i) == True:  
            print(word_list[i])             #I think this is where the problem is???
          
            

    avg = mean(word_length)
    print("Average word length: " + str(avg))
    print("The following words have prime lengths: ")
    
    

while user_input == "quit":
    print("Goodbye!")
    break

Upvotes: 1

Views: 96

Answers (3)

Urmi Patel
Urmi Patel

Reputation: 11

In your second loop value of i will be the length of words and the length of the word_list is different, let's say sentense is : "I am a Student" then list word_length look like [1,2,1,7] and you print word_list[1],word_list[2],word_list[1] and word_list[7], but the length of the word_list is 4 so it will give an IndexError for word_list[7], so the right code is look like as follows:

 for i in range(x):           #here, i starts from 0 and ends at length of word_list
    if is_prime(len(word_list[i])) == True:     
        print(word_list[i])

The following loop is not required.

for i in range(x):
    word_length.append(len(word_list[i]))

Upvotes: 1

Manoj A
Manoj A

Reputation: 432

user_input,PRIME,NON_PRIME = '',[],[]
while user_input != "quit":
    user_input = input("Please enter a random sentence (or type 'quit' to exit):")
    if user_input == "quit":break
    else:
        for i in user_input.split(" "):#user_input text converted to list with separator = ','
            #PRIME CHECK
            if len(i) > 1:
                for j in range(2,len(i)):
                    if (len(i)% j) == 0:
                        NON_PRIME.append([i,len(i)])
                        break
                else:PRIME.append([i,len(i)])
             else:NON_PRIME.append([i,len(i)])
        print(" PRIME:",PRIME,"\n NON PRIME",NON_PRIME)

OUTPUT Please enter a random sentence (or type 'quit' to exit):PRIME CHECKER WITH PYTHON PRIME: [['PRIME', 5], ['CHECKER', 7]]
NON PRIME [['WITH', 4], ['PYTHON', 6]]

Upvotes: 0

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Change the second for loop to -

for i in range(len(word_length)):
    if is_prime(word_length[i]) == True:  
        print(word_list[i])             #I think this is where the problem is???

You are using the actual word length to access an indexed list which doesn't work if the number of elements in the word_list isn't as long as the length of a word. Looping over range(len(word_length)) solves the problem

Upvotes: 0

Related Questions