fork download
import timeit

s = """
import collections
import itertools
def JonClements(iterable):
    i = iter(iterable)
    return any(i) and not any(i)


def only_n(l, testval=True, coerce=bool, n=1):
    counts = collections.Counter()
    def iterate_and_count():
        for x in itertools.imap(coerce,l):
            yield x
            if x == testval and counts[testval] > n:
               break
    counts.update(iterate_and_count())
    return counts[testval] == n

def only_truthy(l, n=1):
    counts = collections.Counter()
    def iterate_and_count():
        for x in l:
            if x: 
                yield True
                if counts[True] > n: break
            else: yield False

    counts.update(iterate_and_count())
    return counts[True] == n

def only_truthy_fixed(l, n=1):
    tcount = 0
    for x in l:
        if x: 
           tcount += 1
           if tcount > n: return False
    return tcount == n

def nisanh(iterable, n=1, m=1): 
    i = iter(iterable) 
    return  m <= sum(any(i) for x in xrange(n+1)) <= n

"""
def nisanh(iterable, n=1, m=1): 
    i = iter(iterable) 
    return  list(any(i) for x in xrange(n+1))
print nisanh([2,3,None])
print nisanh([None,3,None])

def JonClements(iterable):
    i = iter(iterable)
    return any(i) and not any(i)
    
print JonClements([2,3,None])
print JonClements([None,3,None])

number = 500
truelist = "l=[True]*10000"

falselist = "l=[False]*10000"
print timeit.timeit("only_n(l)", s+truelist, number=number)
print timeit.timeit("only_n(l)", s+falselist, number=number)

print timeit.timeit("only_truthy(l)", s+truelist, number=number)
print timeit.timeit("only_truthy(l)", s+falselist, number=number)

print timeit.timeit("only_truthy_fixed(l)", s+truelist, number=number)
print timeit.timeit("only_truthy_fixed(l)", s+falselist, number=number)


print timeit.timeit("JonClements(l)", s+truelist, number=number)
print timeit.timeit("JonClements(l)", s+falselist, number=number)

print timeit.timeit("nisanh(l)", s+truelist, number=number)
print timeit.timeit("nisanh(l)", s+falselist, number=number)
Success #stdin #stdout 6.97s 8888KB
stdin
Standard input is empty
stdout
[True, True]
[True, False]
False
True
0.005126953125
3.65571117401
0.00443387031555
2.84306001663
0.00028395652771
0.275062084198
0.000324010848999
0.046404838562
0.000968933105469
0.0430569648743