I've created a simple program which removes elements of one list from another list using in
method at least two times:
def remove(l_list,s_list):
"""Removes items of s_list from l_list and returns the rest"""
res=[]
for item in l_list:
if item not in s_list:
res.append(item)
return res
I want to replace if not in s_list
operation by the loop "while" and compare complexity of these functions.
So, I've made the following code(doesn't work):
def remove2(l_list,s_list):
res=[]
for item in l_list:
found=False
i=0
while len(s_list)>i and not found:
if item==s_list[i]:
found=True
if not found:
res.append(item)
i+=1
return res
Examples:
>>> remove2([1,2,3],[1,2])
[3]
>>> remove2([1,2,3],[1])
[2,3]
What am I doing wrong? What is wrong with my logic?
You should append the item after the while loop:
def remove2(l_list,s_list):
res=[]
for item in l_list:
found=False
i=0
while len(s_list)>i and not found:
if item==s_list[i]:
found=True
i+=1
if not found:
res.append(item)
return res
Instead of using the found
variable you could simplify this if you use break
:
def remove2(l_list,s_list):
res=[]
for item in l_list:
i=0
while len(s_list)>i:
if item==s_list[i]:
break
i+=1
else:
# this else belongs to the while loop and is executed if and only if
# the loop wasn't terminated by "break".
res.append(item)
return res
There's certainly a logic flaw here:
if item==s_list[i]:
found=True
if not found:
res.append(item)
i+=1
found can never be False at that inner if -- you just set it to True !
Also, do you need to go through this painstaking check? You can "easily" :-) do this with a one-line command. With just list comprehensions:
return [item for item in l_list if item not in s_list]
You could also turn them into sets, take the difference, and convert back to a list:
return list(set(l_list).difference(set(s_list)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.