'Can I fix the index out of range error when I try to get a different word out of the last place of a list with all the same words
For this exercise I can input words until i enter "stop". All the words that I have input will go in to a list. I use a for loop to loop over all the words in the list. If the word isnt the same as the next or previous I "mark" that word.If there are no marked words it wil print out that there are none.If there are 2 or more marked words it will print that it cant be known. This works well until the last word in the list is the "marked" one. I get the error list index out of range. Does anyone see a solution for this? Below I will paste the code.
Thank you!
woorden = []
woord = str(input())
vreemdeEend = 0
vreemdWoord = ""
while woord != "stop":
woorden.append(woord)
woord = str(input())
for index, elem in enumerate(woorden):
if (woorden[index] != woorden[index-1] and woorden[index] != woorden[index+1] and woorden[index-1] != 0):
vreemdeEend += 1
vreemdWoord = woorden[index]
if(vreemdeEend == 1):
print("De vreemde eend in de bijt is " + vreemdWoord)
elif(vreemdeEend >= 2):
print("vreemd eend is onbeduid")
else:
print("er is geen vreemd eend")`
I tried to check if the index is at the last place that it would check the previous 2 words to see if they are the same. But this didnt have any effect
Solution 1:[1]
woorden = []
woord = str(input())
vreemdeEend = 0
vreemdWoord = ""
while woord != "stop":
woorden.append(woord)
woord = str(input())
if len(woorden)>0:
woorden.append(woorden[-1] + "DIFRENCE")
for index, elem in enumerate(woorden):
if (woorden[index] != woorden[index-1] and woorden[index] != woorden[index+1] and woorden[index-1] != 0):
vreemdeEend += 1
vreemdWoord = woorden[index]
if(vreemdeEend == 1):
print("De vreemde eend in de bijt is " + vreemdWoord)
elif(vreemdeEend >= 2):
print("vreemd eend is onbeduid")
else:
print("er is geen vreemd eend")`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammad sadegh borouny |
