'Check if a value is in a list of routes, if yes new list append 1, else 0

I'm trying to create an automatic method check if a value i exists in a list[list] of routes. If so, the new bir list (check the presence of the location by each route) append(1) if location exists on the route, or otherwise append(0).

Example:

routes=[[(0, 1), (1, 3), (3,0)], [(0,2), (2,0)]] #2 routes

My attempt:

bir=[]
for i in range(1,N): # N=4 (not counting the 0 - depot).
    if i in range(len(routes)):
        bir[i].append(1)
    else:
        bir[i].append(0)

I also tried Python list comprehension, but without success.

What I'd like to get was something like this:

bir=[[1,0],[0,1],[1,0]]

That is, it is clear that, for example, location i=1 is present on route 1 and not on route 2, while location i=2 is only present on route 2. Location i=3, in turn, is also only present on route 1 and not on route 2.

Any suggestions for my problem?



Solution 1:[1]

This genuinely hurt my head to get around, thanks for the question was fun to work out!

routes = [[(0, 1), (1, 3), (3, 0)], [(0, 2), (2, 0), (0, 0)]]

bir = []
# check values 1, 2, 3
for i in range(1, 4):
    # check every route
    for x in range(len(routes)):
        # check if bir contains an empty list for the value we are currently checking
        try:
            bir[i-1]
        # if there is no empty list, create one
        except IndexError:
            bir.append([])
        # check if the route exists
        try:
            # if our value exists in the route then append 1
            if i in routes[x][i - 1]:
                bir[i-1].append(1)
            # if the value does not exists append 0
            else:
                bir[i-1].append(0)
        # if the route does not exist append 0
        except IndexError:
            bir[i - 1].append(0)

print(bir)

Solution 2:[2]

bir = []
N = 4

for i in range(1, N):
    bir.append([])  # insert a new sub-list for results
    for route in routes:
        if any(i in point for point in route):
            # 'i-1' because of 0-indexing
            # indexing is needed to insert into sub-lists
            # instead of appending directly to 'bir'
            bir[i-1].append(1)
        else:
            bir[i-1].append(0)

Edit to say that this can be cleaned up a bit if you're okay with bir containing True/False instead of 1/0:

for i in range(1, N):
    bir.append([])  # create a new sub-list for results
    for route in routes:
        bir[i-1].append(any(i in point for point in route))

# results in -> bir = [[True, False], [False, True], [True, False]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2