简体   繁体   中英

Find all possible replacements for 1s and 0s in a list

Input:

table = [
    [1, ''],
    ['', 0]
]

Desired output: [[[1, 0], [0, 0]], [[1, 0], [1, 0]], [[1, 1], [0, 0]], [[1, 1], [1, 0]]]

Tried to do it with recursion like this:

def get_tables(tab, out_tab):
    changes = 0
    for row_i, row in enumerate(tab):
        for val_i, val in enumerate(row):
            if val == '':
                changes = 1
                tab[row_i][val_i] = 0
                get_tables(tab, out_tab)
                tab[row_i][val_i] = 1
                get_tables(tab, out_tab)
    if changes == 0:
        out_tab.append(tab)

But it returns only 1s

Edit: So the logic is: find '' in list and then create two lists, one with 1 instead of '' and one with 0 (like [1, ''] to [1, 0] and [1, 1]). Do the same operation with those two lists, and continue until there's no ''. Return all this lists in one.

Not the most efficient solution, but it works:

table = [
    [1, ''],
    ['', 0]
]

import copy

# locations where element is ''
locs = [[idx_r, idx_c] for idx_r, row in enumerate(table) for idx_c, element in enumerate(row) if element == ''] 
len_locs = len(locs)
tables = []

for i in range(2 ** len_locs): # for n locations, we have 2**n permutations of 1 and 0
    table_copy = copy.deepcopy(table)
    permutation = list(map(int, f'{i:0{len_locs}b}')) # convert i to the binary to get current permutation
    for it, (idx_r, idx_c) in enumerate(locs):
        table_copy[idx_r][idx_c] = permutation[it]
    tables.append(table_copy)

print(tables)
>>> [[[1, 0], [0, 0]], [[1, 0], [1, 0]], [[1, 1], [0, 0]], [[1, 1], [1, 0]]] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM