I just want to know How to iterate list backwards using for loop. Please look at below code.
mystring="My name is Rohit Kaushik. Rohit loves to play cricket"
mylist=mystring.split(' ')
for i in mylist:
for j in ?
In the J loop I want to check the occurrence of the word that i loop holds Let's Consider
When indexing of i
reaches to 5
(i.e Second occurrence of Rohit
) , I want to run the j
loop to check whether Rohit
has occurred previously or not in mylist and to check that I need to run the j
loop backwards in mylist
. If Rohit has occurred previously I want to break the loop.
Please help.
P.S - I am very new to Python, please don't downvote this question
CodePudding user response:
You don't need a loop, use the in
operator to test a slice of the list.
for i, word in enumerate(mylist):
if word in mylist[:i]:
// do something
i
is the current index in the list, and mylist[:i]
is the slice of the list before this.
But rather than searching the list, you can put each word in a set
, and check if the word is in there. Searching a set is faster than searching a list.
word_set = set()
for word in mylist:
if word in word_set:
// do something
word_set.add(word)
CodePudding user response:
Although you don't need to, if you really wanted to do the for loop in reverse, you can do:
for x in range(len(mylist)-1, -1, -1):
print(mylist[x])
# Do something else
CodePudding user response:
You can do something like this:
mystring="My name is Rohit Kaushik. Rohit loves to play cricket"
mylist=mystring.split(' ')
mySet=set()
for i in mylist:
if i in mySet:
break;
else:
mySet.add(i);
This will cut down the execution time since we do not need to iterate to all the previous values in array to check weather it is occurred already. Set will allow you check weather or not current element occurred previously in constant time i.e. O(1) Overall time complexity of above program is O(n).