John John - 6 months ago 33
Python Question

Program outputs 1131 not 1121

I have ran into a logic error that I cannot solve and would like some assistance towards it.
Here's my code

Mysentence = MySentence
print(Mysentence)
MysentenceList = Mysentence.split()
List = []

for k in MysentenceList:
position = MysentenceList.index(k)
position = position + 1
position = str(position)
List.append(position)

Number = ",".join(TheList)
print(Number)
Number = "\n" + Number
fileName = input("File Name: ")
fileName = fileName + ".txt"


Basically cannot handle unique words

Answer

If you want to assign each word a "unique id", you'd have to manage this in another data structure. Another list would do the trick:

UniqueWords = []
for k in ThesentenceList:
    if k in UniqueWords:
        position = UniqueWords.index(k)
    else:
        position = len(UniqueWords)
        UniqueWords.append(k)
    position = position + 1
    position = str(position)
    TheList.append(position)
Comments