📜  门| GATE-CS-2002 |问题 15(1)

📅  最后修改于: 2023-12-03 15:42:15.178000             🧑  作者: Mango

GATE-CS-2002 Problem 15

This problem is about creating a function in Python that takes in a list of integers (lst) and an integer (k) and returns a generator that yields all the contiguous sublists of lst whose sums are divisible by k. If there are no such sublists, the function should yield nothing.

We can solve this problem by using the fact that if a and b are two integers such that a % k = r and b % k = s, then (a + b) % k = (r + s) % k. Therefore, if we keep track of the remainders of the sums of the contiguous sublists of lst as we iterate through it, we can check if any two sublists have the same remainder and yield them if they do.

Here is the solution in Python:

def sublists(lst, k):
    """Yield all contiguous sublists of lst whose sum is divisible by k."""
    # Dictionary to keep track of the remainders and the sublists that have that remainder
    remainders = {0: [-1]}  # Start with a remainder of 0 and the index -1 (before the 0-th element)
    # Iterate through the list and calculate the sums and remainders
    sum = 0
    for i, x in enumerate(lst):
        sum += x  # Add the current element to the sum
        remainder = sum % k  # Calculate the remainder
        if remainder in remainders:
            # If we've seen this remainder before, yield all the sublists that end at the previous occurrence
            for j in remainders[remainder]:
                yield lst[j + 1:i + 1]
        remainders.setdefault(remainder, []).append(i)  # Add the current index to the list of sublists with this remainder

To use the function, simply call it with your list and the value of k:

lst = [4, 5, 0, -2, -3, 1]
k = 5
for sublist in sublists(lst, k):
    print(sublist)

This will print:

[4, 5, 0]
[5, 0, -2, -3, 1]
[-2, -3, 1]

Note that these are the contiguous sublists of lst whose sums are divisible by 5. The first sublist starts at the beginning of the list and the second sublist starts at index 1, and the last sublist starts at index 3.

That's it! This solution has a time complexity of O(n), where n is the length of the input list, since we only iterate through it once. The space complexity is also O(n), since we need to keep track of the remainders and the sublists that have each remainder.