views:

98

answers:

5

I have a list:

a = [1, 2, 6, 4, 3, 5, 7]

Please, explain mne how to check whether element appears only once in in the list?

Please, also explain if all elements from 1 to len(a) are in the list. For inctance, in list 'a' element from 1 to 7 are in the list, but if the list is b = [1, 4, 3, 5], then not all elements from 1 to 4 are not in the list.

Thank you!

+5  A: 

For your first question if your elements are hashable you can create a set containing the elements and check its length:

len(set(a)) == len(a)

Alternatively you can use this function which can give better performance than the above if the result is False (but worse performance when the result is True):

def are_all_elements_unique(l):
    seen = set()
    for x in l:
        if x in seen:
            return False
        seen.add(x)
    return True
Mark Byers
+1  A: 

When I read your question, I took a different meaning from it than mark did. If you want to check if a particular element appears only once, then

def occurs_once(a, item):
    return a.count(item) == 1

will be true only if item occurs in the list exactly once.

See Pokes answer for the second question

aaronasterling
Aren't you assuming that the list doesn't contain doubles? Also, shouldn't you only check whether every element in `range(1,n+1)` is in `a`?
Herman
`range` is a generator in newer Pythons.
poke
Oh I see, I think we understood the question differently. I thought all the numbers from `1 - n` should be contained in the list, regardless of order and position, and might be mixed with other numbers as well.
Herman
@Herman, they couldn't possibly be mixed with other numbers regardless of how you read the question. `a = [1, 2, ..., len(a)]` must contain one copy of each number between 1 and `len(a)` if there is another number in there, then it doesn't satisfy the requirements. My method was wrong to not check min and max though. for example `[0, 1, 2, 7]` sums to 7 and beats my test without the check.
aaronasterling
+2  A: 
len( set( a ) ) == len( a )

for the first question, and

( len( set( a ) ) == len( a ) == max( a ) ) and min( a ) == 1

for the second.

poke
The second answer requires that all elements in `a` are integers.
J.F. Sebastian
I'd like this a lot more if it was written in pep8 style. As it stands, the code looks horrible.
Blue Peppers
@J.F. Sebastian: Yes, but I simply assumed that from the question :) – @Blue Peppers: Sorry, but I use too many different languages to have a different coding style for each one; and that's simply how I like it the most.
poke
+1  A: 

i understood you want something like that:

[x for x in a if a.count(x) == 1]
Ant
+3  A: 

For the second question you might want to check

sorted(a) == range(1, len(a) + 1)
jellybean