1

I have an ascending list of integers e that starts from 0 and I would like to have a binary list b whose i-th element is 1 if and only if i belongs to e.

For example, if e=[0,1,3,6], then this binary list should be [1,1,0,1,0,0,1], where the first 1 is because 0 is in e, the second 1 is because 1 is in e, the third 0 is because 2 is not in e, and so on.

You can find my code for that below.

My question is: is there something built-in in python for that? If not, is my approach the most efficient?

def list2bin(e):
b=[1]
j=1
for i in range(1, e[-1]+1):
    if i==e[j]:
        b.append(1)
        j+=1
    else:
        b.append(0)     
return(b)

2 Answers 2

7

This can be done with a list comprehension, and in case e is huge then better convert it to a set first:

>>> e = [0, 1, 3, 6]
>>> [int(i in e) for i in xrange(0, e[-1]+1)]
[1, 1, 0, 1, 0, 0, 1]

The in operator returns True/False if an item is found in the list, you can convert that bool to an integer using int. Note that for lists the in is O(N) operation, so if e is large then converting it to a set will provide you much more efficiency.

Sign up to request clarification or add additional context in comments.

5 Comments

Just a comment, xrange doesn't exist in Python3, other than that the solution is beautiful.
@Ashwini Thank you! Unfortunately I do have to use lists. e is not going to be that huge (maximum 150 elements, although later on I may try with around 400), but this will be called over and over, many times (I'm running a reccursive algorithm that will be running for weeks and what I'm asking will be in every iteration). Do you think it makes sense to turn the list into a set every time, in my case?
@geo909 timeit results: searching 400 in a list of size 400 takes 12 micro-seconds, while a set takes just 200 nano seconds.
@Ashwini Thanks.. And although it's obviously more elegant, your solution is better in terms of effiency, right?
@geo909 No, the list based version is not better than your solution theoretically(as it is an O(N**2)) and will be slow for huge lists. But the set version will be almost equivalent to your solution.
0

I don't think there are a built-in way to do that. But you can use List Comprehensions:

a = [ 1 if i in e else 0 for i in range(1, e[-1]+1) ]

Get fun.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.