Home > front end >  Find out different lengths with values in a two-dimensional list, depending on the number given as a
Find out different lengths with values in a two-dimensional list, depending on the number given as a

Time:01-25

Suppose I have a two-dimensional list mixed with True and False. I would like to create a function that gives me an additional parameter, which should be the number of elements to be output. The output should be like this: For example, if I enter 3 as a number, the row and column in which 3 x True are located one after the other should be displayed. So just the row and the first column For example, in the list below: 3 x True in row: 1 and col: 3

lst = [[False, True, False, True, True, False],
        [False, True, False, True, True, True],
        [True, False, True, True, True]]

I've tried several options, but never found a solution. I have another small example here, but of course I get the wrong output:

def baz(count):
    for row in range(len(lst)):
        for col in range(len(lst[row])):
            if lst[row][col] == lst[row][(col   count) % len(lst[row])] and lst[row][col] is True:
                return (row, col)


print(baz(3))

CodePudding user response:

You can use all to simplify the code, it returns True if all values in the iterable are True otherwise False.

lst = [[False, True, False, True, True, False],
        [False, True, False, True, True, True],
        [True, False, True, True, True]]

def baz(count):
    for row in range(len(lst)):
        if len(lst[row]) < count:
            continue
        for col in range(len(lst[row])-count 1):
            if all(lst[row][col:col count]):
                return (row, col)
    return None


print(baz(3))
print(baz(2))

prints -

(1, 3)
(0, 3)

Note that there can be multiple matches for a given count, so the function returns the first match found.

Also, for high values of count, above code is not optimal(since in each step we are doing O(count) work when we call all(). So in case you are worried about performance you can use the below function instead -

def baz(count):
    for row in range(len(lst)):
        if len(lst[row]) < count:
            continue
        prev_true = -1
        for col in range(len(lst[row])):
            if not lst[row][col]:
                prev_true = col
                continue
            if col - prev_true == count:
                return (row, col-count 1)
    return None
  •  Tags:  
  • Related