Home > database >  function that will remove every sublist that is **inside** of other list
function that will remove every sublist that is **inside** of other list

Time:06-15

if i have this list of lists

[[8,7,5,6,8],[6,4,6,3],[4,6],[8,7,5,6],[7],[6,4,35]]

what do i have to do to return this one: [[8,7,5,6,8],[6,4,35]] ?? what do i mean by that is i want a function that will remove every sublist that is inside of other list.

i already have the function that will see if that happens

def DNAoccursQ(w1,w2):
if len(w1)==len(w2):
    i=0
    while i<len(w1):
        if w1[i] != w2[i]:
            return False
        i =1
    return True

elif len(w1)>len(w2):
    return False

else:
    for i in range(len(w2)-1):
        if w2[i] != w1[0]:
            i =1
        else:
            p=i
            t=0
            for t in range(len(w1)):
                if w1[t] == w2[p]:
                    p  = 1
                    t =1
                elif w1[t]!=w2[p]:
                  return False
            return True
return False

CodePudding user response:

If you don't have like a huge list you could just check each list against every other list:

def is_subsequence(a: list[int], b: list[int]) -> bool:
    """Returns whether b is a subsequence of a."""
    return any(a[i:i   len(b)] == b for i in range(len(a) - len(b)   1))


def get_unique_lists(nums: list[list[int]]) -> list[list[int]]:
    """Removes any lists that exist as a sublist of another list in nums."""
    return [
        b for i, b in enumerate(nums)
        if all(not is_subsequence(a, b) for j, a in enumerate(nums) if i != j)
    ]


def main() -> None:
    nums = [[8, 7, 5, 6, 8], [6, 4, 6, 3], [4, 6], [8, 7, 5, 6], [7], [6, 4, 35]]
    print(f'{nums = }')
    new_nums = get_unique_lists(nums)
    print(f'{new_nums = }')


if __name__ == '__main__':
    main()

Output:

nums = [[8, 7, 5, 6, 8], [6, 4, 6, 3], [4, 6], [8, 7, 5, 6], [7], [6, 4, 35]]
new_nums = [[8, 7, 5, 6, 8], [6, 4, 6, 3], [6, 4, 35]]

CodePudding user response:

    a = [[8,7,5,6,8],[6,4,6,3],[4,6],[8,7,5,6],[7],[6,4,35]]
    answer = [a[0],a[-1]] = [[8,7,5,6,8],[6,4,35]]
  • Related