这可能不是特定于Python的问题,但确实如此:
我正在尝试解决一种类型的数值问题,其中必须显示列表a = [a_1,a_2,a_3,...]中的哪些元素具有一些属性X。但是,当我证明它用于一些a_n,我有时还会为列表中的其他元素a_m证明这一点。因此,为了加速算法,我不想再次测试这些元素。
现在,我可以创建一个列表has_property_X,并在遍历a的同时测试每个元素是否在列表中(并在测试每个元素之后填充该列表)。但是,在执行此操作时,我仍然必须遍历每个元素。
有没有更聪明的方法?
答案 0 :(得分:2)
您可以做的一件事是用查找表(字典)替换列表has_property_X
。查找表将跟踪每个a_i
。密钥将为a_i
,值将为
None
,如果尚未处理该元素True
,如果元素具有属性False
,如果元素没有属性。这为检查元素是否已被处理提供了复杂度O(1)。看起来像这样:
a = [1, 2, 3, 4, 5] # your list `a`
lookup_table = {a_i: None for a_i in a}
for element in a:
if lookup_table[element] is None:
# determine if element has the property
element_has_property = False
# if, in the process, you determine that another element `a_m` also has the property,
# then set lookup_table[a_m] = True
lookup_table[element] = element_has_property
# assemble list of elements which have the target property
has_property_x = [a_i for a_i in lookup_table if lookup_table[a_i] ]
答案 1 :(得分:0)
我认为您的方法是正确的,因为时间成本是在计算每个a_i
而不是在list循环中发生的。如果您在列表a
和停止列表has_x_property
(如果重复的值无关紧要,则返回一个集合)上循环
for elem in a:
if elem not in has_property_x:
algoritm(elem)
update(has_property_x)
答案 2 :(得分:0)
想一想的时候,我想到了以下方法:
a = [a_1,a_2,a_3...] #the list
has_property_X = []
while a!=[]:
#algorithm that tests and removes a[0] and appends to has_property_X the elements that
#do and removes them from a as well
我不知道这种方法有多好(与zachdj的方法相比)。但是,它确实回答了这个问题,而且我不知道为什么它会变得更糟...