My task is to:
Develop a program that identifies individual words in a sentence, stores these in a list and replaces each word in the original sentence with the position of that word in the list.
For example, the sentence ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY contains the words ASK, NOT, WHAT, YOUR, COUNTRY, CAN, DO, FOR, YOU
The sentence can be recreated from the positions of these words in this list using the sequence 1,2,3,4,5,6,7,8,9,1,3,9,6,7,8,4,5
I've done the first part of the task and so far I have this code:
sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR
YOUR COUNTRY"
s = sentence.split()
positions = [s.index(x)+1 for x in s]
my_list = ['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR',
'YOU', 'ASK', 'WHAT', 'YOU', 'CAN', 'DO', 'FOR', 'YOUR', 'COUNTRY']
unique = []
[unique.append(item) for item in my_list if item not in unique]
print("The sentence",sentence,"contains the words",unique)
print("It can be recreated from the positions of the words in this
list",s,"using the sequence",positions)
Is this considered efficient? How can I make it more efficient?
However, my problem is the rest of the task:
Save the list of words and the positions of these words in the sentence as separate files or as a single file.
I have no idea what it means. I did some research and I found out that it involves reading and writing to a file, but I don't have a clue what to do next.
Nevertheless I came up with this:
my_list = ['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR',
'YOU', 'ASK', 'WHAT', 'YOU', 'CAN', 'DO', 'FOR', 'YOUR', 'COUNTRY']
with open("task2.txt", 'w') as f:
f.write("\n".join(map(str, my_list)))
But I don't know what it does or how it relates to the task??? I need to be able to explain my code which I can't do since I don't understand it.
Can someone please fix my code? Thank you