2

Possible Duplicate:
python takes list and returns only if negative value also exists using set

I'm having problems with another homework problem.

By using a set, write a method negated(a) that takes a list, a, as an argument and returns a list containing only the elements x such that -x is also in a

His example shows that the input is

[-6, 8, 7, 3, 2, -9, 1, -3, 2, -4, 4, -8, 7, 8, 2, -2, -7, 0, 1, -9, -3, -7, -3, -5, 6, -3, 6, -3, -10, -8]

and the output is

[-6, 8, 7, 3, 2, -3, 2, -4, 4, -8, 7, 8, 2, -2, -7, 0, -3, -7, -3, 6, -3, 6, -3, -8]

I was able to figure out how to do it without using a set with

return [x for x in a if -x in a]

I'm just having problems implementing a set into the problem. Can someone give me the steps to take, how I should tackle the problem... I'm not looking for the complete work, but it would be nice to see how you do it also.

4

2 回答 2

2

您的代码按原样工作。您需要做的就是将列表更改为一组。

def negate(a) :
  return [x for x in a if -x in a]

a = set()
a.add(1)
a.add(2)
a.add(-1)
print negate(a)

演示

于 2012-10-15T01:43:05.970 回答
1

这是您需要实现的算法:

  1. 遍历列表中的所有元素
  2. 当你考虑每个单独的元素时,检查它的否定是否存在于列表中
  3. 如果否定存在于列表中,则保留它
  4. 如果否定在列表中不存在,请不要保留它。

在迭代列表时从列表中删除元素通常是一个坏主意,因此最好创建一个新的空列表并继续添加(或不添加)它。

def filterNegs(L):
    answer = []
    for i in L:
        if -1*i in L:
            answer.append(i)
    return answer

这是相同的列表理解:

return [i for i in a if -1*i in a]

但是,当您这样做时会出现性能问题。检查元素是否在列表中是 O(n) 操作和 O(1) 在集合中。所以,最好先L变成一个集合:

def filterNegs(L):
    L = set(L)
    answer = []
    for i in L:
        if -1*i in L:
            answer.append(i)
    return answer

这是相同的列表理解:

L = set(L)
return [i for i in a if -1*i in a]

希望这可以帮助

于 2012-10-15T01:42:15.200 回答