solution 1. brute-force recursion and remove duplicates
You can eliminate duplications using set
.
But you cannot make set
of list
s since list
is not hashable.
And for efficiency, you can gather index-pairs first, and then slice:
def num_sub_array(array):
return [
array[i:j] for i, j in build_pair_set(0, len(array))
]
def build_pair_set(start: int, end: int) -> set:
return set() if start == end else (
{(start, end)}
| build_pair_set(start + 1, end)
| build_pair_set(start, end - 1)
)
print(sorted(num_sub_array([1, 2, 3, 4])))
output:
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
solution 2. recursion without redundancy
def num_sub_array(array):
if not array:
return []
return [array[i:] for i in range(len(array))] + num_sub_array(array[:-1])
print(sorted(num_sub_array([1, 2, 3, 4])))
output:
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
Actually, solution 2's num_sub_array
has a tail recursion. So you can change it to loop.
Solution 3. Loop
def num_sub_array(array):
return [
array[i:j]
for i in range(len(array))
for j in range(i + 1, len(array) + 1)
]
print(sorted(num_sub_array([1, 2, 3, 4])))
output:
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
I used sorted
for comparing two methods. It is not necessary.