Is there any way of removing an element from a list in python in O(1) complexity.i.e., remove(value): this searches linearly through the list and removes right.? So, is there any way to delete an element in O(1) complexity by specifying index or value?
When input list of size 100000 is given to the following code,it is exceeding time limit..,even after using "del".
l=map(int,raw_input("").split(" "))
n=l[0]
k=l[1]
s=map(int,raw_input("").split(" "))
s=sorted(s)
count=0
tree=[]
while len(s)>0:
poset=[]
indices=[]
i=0
poset.append(s[i])
indices.append(0)
j=i+1
while j<len(s):
if s[j]==k*s[i]:
poset.append(s[j])
indices.append(j)
i=j
j+=1
tmp=0
for i in indices:
del s[i-tmp]
tmp+=1
tree.append(poset)
for i in tree:
if len(i)%2==0:
count+=(len(i))/2
else:
count+=(len(i)+1)/2
print count
len(s)is calculated, it's an O(N) calculation. So each time it starts one of yourwhileloops it recalculateslen(s). You can replacewhile len(s)>0:withwhile s:Thej<len(s)can be sped up by settings_length = len(s)and then dowhile j<s_length. If we know the goal of your code and the indenting is clean, I think we'll be able to give more suggestions.forloop:for i in tree:i_length = len(i)and then replace all thelen(i)withi_length. So I think the most obvious problem with your code is that you repeatedly calculatelen(list)for some list. That's very slow.