I'm new to python and continuously learning to build better codes in python. I have two lists; one with indexes stored in x variable, where the indexes in the x represents index of tuples in list named bb with string ('IN') and surrounded on both sides at least with one tuple containing 'NN'.
What i'm trying to get from the below code is, From every index mentioned in x in bb, how many continuous strings starting with 'NN' are present on both sides of the string tuple in bb list.
I tried the below code, but the code isn't efficient enough. Anybody please help me in making the code efficient.
bb = [('The', 'RB'),
('company', 'NN'),
('whose', 'NNS'),
('stock', 'IN'),
('has', 'NNP'),
('been', 'NNS'),
('on', 'NNP'),
('tear', 'VBJ'),
('this', 'VB'),
('week', 'NNS'),
('already', 'NN'),
('sells', 'IN'),
('its', 'NNP'),
('graphics', 'NNS'),
('processing', 'VB'),
('units', 'VBJ'),
('biggest', 'NNS'),
('cloud', 'NN'),
('companies', 'IN'),
('just', 'NNP'),
('that', 'IN')]
def solvr(bb):
x = []
for i in range(len(bb)-1):
if bb[i][1] == 'IN':
if 'NN' in (bb[i-1][1]) and 'NN' in (bb[i+1][1]):
x.append(i)
#===============================
for i in range(len(bb)-1):
if i in x:
k=[]
front = bb[i+1:]
v = 0-i
back = bb[:-v]
#======================
for i in back:
if 'NN' in i[1]:
k.append(i[0])
[[] for i in k]
#================================
for i, j in enumerate(front):
if front[i][1][:2] == 'NN':
k.append(front[i][0])
else:
break
return(k)
>> solvr(bb)
output:
['company',
'whose',
'has',
'been',
'on',
'week',
'already',
'its',
'graphics',
'biggest',
'cloud',
'just']
My expectation from code is to get each iteration result in new list with also 'IN' string included in every list.
[['company', 'whose', 'stock', 'has', 'been', 'on'],
['week', 'already', 'sells', 'its', 'graphics'],
['biggest', 'cloud', 'companies', 'just']]
Would be thankful if someone provides any changes to my code.