Skip to content Skip to sidebar Skip to footer

Modify For List Output In Recursion

In Find all possible combinations that overlap by end and start, we get the following program that gets all possible combinations of ranges that only overlap by end and start value

Solution 1:

Right now, what the code does is create a giant string because you start with a string and cast every tuple into a string before concatenating everything together. Instead, what you can do is pass in an empty list and add tuples to the list until you finish your combination. Once you get to the end of the combination, add it to a global array that holds all your combinations.

# Create a global array to hold all your results.
results = []

defgetAllEndOverlappingIndices(lst, i, l):
    r = -1if i == len(lst):
        if l:
            # Instead of printing final combination, add the combination to the global list
            results.append(l)
        return

    n = i + 1while n < len(lst) and r > lst[n][0]:
        n += 1
    getAllEndOverlappingIndices(lst, n, l)

    n = i + 1
    r = lst[i][1]
    while n < len(lst) and r > lst[n][0]:
        n += 1# Wrap the tuple in the list to take advantage of python's list concatenation
    getAllEndOverlappingIndices(lst, n, l + [lst[i]])

indices = [(0.0, 2.0), (0.0, 4.0), (2.5, 4.5), (2.0, 5.75), (2.0, 4.0), (6.0, 7.25)]
indices.sort()
# Pass in an empty list here instead of an empty string
getAllEndOverlappingIndices(indices, 0, [])

Output:

[[(6.0, 7.25)], [(2.5, 4.5)], [(2.5, 4.5), (6.0, 7.25)], [(2.0, 5.75)], [(2.0, 5.75), (6.0, 7.25)], [(2.0, 4.0)], [(2.0, 4.0), (6.0, 7.25)], [(0.0, 4.0)], [(0.0, 4.0), (6.0, 7.25)], [(0.0, 2.0)], [(0.0, 2.0), (6.0, 7.25)], [(0.0, 2.0), (2.5, 4.5)], [(0.0, 2.0), (2.5, 4.5), (6.0, 7.25)], [(0.0, 2.0), (2.0, 5.75)], [(0.0, 2.0), (2.0, 5.75), (6.0, 7.25)], [(0.0, 2.0), (2.0, 4.0)], [(0.0, 2.0), (2.0, 4.0), (6.0, 7.25)]]

Output editted for visiblity:

[[(6.0, 7.25)],
[(2.5, 4.5)],
[(2.5, 4.5), (6.0, 7.25)],
[(2.0, 5.75)],
[(2.0, 5.75), (6.0, 7.25)],
[(2.0, 4.0)],
[(2.0, 4.0), (6.0, 7.25)],
[(0.0, 4.0)],
[(0.0, 4.0), (6.0, 7.25)],
[(0.0, 2.0)],
[(0.0, 2.0), (6.0, 7.25)],
[(0.0, 2.0), (2.5, 4.5)],
[(0.0, 2.0), (2.5, 4.5), (6.0, 7.25)],
[(0.0, 2.0), (2.0, 5.75)],
[(0.0, 2.0), (2.0, 5.75), (6.0, 7.25)],
[(0.0, 2.0), (2.0, 4.0)],
[(0.0, 2.0), (2.0, 4.0), (6.0, 7.25)]]

Post a Comment for "Modify For List Output In Recursion"