I have a exclusion_list = [‘and’, ‘or’, ‘not’]
My string is 'Nick is not or playing football and or not cricket'
- In the string if exclusion_list is coming
togetherthen it should take first one
My expected out is 'Nick is not playing football and cricket'
Code is below
search_value = 'Nick is not or playing football and or not cricket'
exclusion_list = ['and', 'or', 'not']
search_value_2 = search_value.split(' ')
for i in range(0,len(search_value_2)-2):
if search_value_2[i] in exclusion_list and search_value_2[i+1] in exclusion_list:
search_value_2.remove(search_value_2[i+1])
' '.join(search_value_2)
My out>> ‘Nick is not playing football and not cricket’
Expected out> ‘Nick is not playing football and cricket’
Basically I need to call recursively till no exlusion_list is coming together in string
>Solution :
First let’s use a more meaningful name for search_value_2. What does this list contain? Words!
So we call this list words.
Since the code tries to access the element at i + 1 (where ìis the index of the word in the list) it shouldn't run up tolen(words) – 2butlen(words) – 1`.
search_value = 'Nick is not or playing football and or not cricket'
exclusion_list = ['and', 'or', 'not']
words = search_value.split(' ')
for i in range(len(words) - 1):
if words[i] in exclusion_list and words[i + 1] in exclusion_list:
words[i + 1] = ''
print(' '.join(words))
Now we get Nick is not playing football and not cricket. At least we have a result, but it’s still not correct. We can avoid the extra space by not joining empty words. This means changing ' '.join(words) to ' '.join((word for word in words if word)).
Then we have to take into account that more than two words from the exclusion list follow each other. The simple words[i] in exclusion_list doesn’t work because that word might have been overridden with an empty string during the last loop.
So this has to be changed to (words[i] == '' or words[i] in exclusion_list).
search_value = 'Nick is not or playing football and or not cricket'
exclusion_list = ['and', 'or', 'not']
words = search_value.split(' ')
for i in range(len(words) - 1):
if (words[i] == '' or words[i] in exclusion_list) and words[i + 1] in exclusion_list:
words[i + 1] = ''
print(' '.join((word for word in words if word)))
Final result: Nick is not playing football and cricket