tags:

views:

69

answers:

3

I got a problem:

keys here is a list.

keys = [(6,4) , (6,8)]

The entries in the keys can be 4,5...or watever

Now, I have to pick up only 1 from it.So I used:

root = keys[0]
print root

output: (6,4)

Now I have to make a set which is empty, say,...

closed = set()

for u,v of root:
   if v not in closed:
      closed.add(v)
      for val in closed:
         print val

It should add values to the set i.e 6 and 4. How should I implement it? The above method is right or wrong? I tried, but not giving me the right ans

A: 

You could try this to add the 6 and the 4 into your set:

closed = set()
closed.add(root[0])
closed.add(root[1])

But maybe you should explain a bit more, what you are trying to do. Then we could help you better.


The line for u,v of root: will not compile. (6,4) is a tuple, which is an immutable sequence type. You can get its values with the [] operator (like in my code above) or you could unpack it like this:

(u,v) = root

If you want to add both values, you should include this call in your code:

closed.add(u)

The code:

if v not in closed:
    closed.add(v)

is equivalent to:

closed.add(v)

A set ensures, that each element is contained only once.

Ralph
basically, root = (6,4) has 2 values in it. I need to check if both of these values are inside my set or not. But it is giving me a type error: unpack nonsequence
Shilpa
2 values= 6 and 4
Shilpa
A: 

If I understand you correctly you want to do:

keys = [(6,4) , (6,8)]
closed = set()
map(closed.update, keys)

By the way, this is a bit redundant:

if v not in closed:
    closed.add(v)

You can just do:

closed.add(v)

If v is in closed already, nothing happens.

DiggyF
+2  A: 
>>> keys = [(6,4) , (6,8)]
>>> root = keys[0]
>>> closed = set()
>>> closed.update(root)
>>> closed
{4, 6}
gnibbler