Reputation:
So I'm making a program that rewrites a sentence as the indices of all the unique words in the sentence (e.g the sentence "quick brown fox brown fox" would be rewritten as "12323"). Here's what I've got so far;
sentence=input("please input your sentence")
sentence=sentence.split(" ")
unique=[]
positions=[]
print(sentence)
for i in sentence:
if i in (unique):
print(" the item " + i + " has been repeated")
ind = i.index(i)
positions.append(ind)
else:
unique.append(i)
print(unique)
print(positions)
I want to get the index of "i" and append it to the list "positions", but when I run the above code with the sentence "quick brown fox brown fox" I get this output for "positions";
[0, 0]
The output I want would look more like this;
[2, 3]
It seems like such a simple problem but for the life of me I can't figure it out. The built in "enumerate" function doesn't fit the problem as it makes it so that "i" will never be found in "unique" and therefore "positions" would be empty.
Upvotes: 0
Views: 740
Reputation:
Okay guys, thanks for all your contributions but I've found an incredibly simple solution:
sentence = input("Please input your sentence: ")
sentence = sentence.slpit(" ")
for i in sentence:
print(sentence.index(i)+1)
The output for the sentence "quick brown fox brown fox" being:
1
2
3
2
3
Which is exactly what I needed.
Upvotes: 0
Reputation: 865
Changing i.index(i)
sentence.index(i)
fixes your code:
sentence="quick brown fox brown fox" #input("please input your sentence")
sentence=sentence.split(" ")
unique=[]
positions=[]
print(sentence)
for i in sentence:
if i in (unique):
print(" the item " + i + " has been repeated")
ind = sentence.index(i)
positions.append(ind)
else:
unique.append(i)
print(unique)
print(positions)
Note that the output is [1,2] instead of your desired [2,3] because of the python convention of starting arrays from 0. If you want [2,3] as an answer your can simply set positions = positions + 1
Upvotes: 0