Skip to content

Instantly share code, notes, and snippets.

@anibalsolon
Last active April 30, 2017 22:36
Show Gist options
  • Save anibalsolon/a994bb9d6d6f8786d5d7b765c9151be5 to your computer and use it in GitHub Desktop.
Save anibalsolon/a994bb9d6d6f8786d5d7b765c9151be5 to your computer and use it in GitHub Desktop.
Faça uma função recursiva em Python que recebe uma lista L e retorna uma lista composta por todas as sublistas de L.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def compositions(l, init=None):
# Use init argument or
# start an empty list (for the first list)
init = init or []
yield init
# Recursion break condition, when there is
# no remaining combinations to create
if len(l) == 0:
return
# Iterate through the remaining elements
for i, v in enumerate(l):
# Add the element to the list, and create new
# combinations with the remaining elements
for ret in compositions(l[i+1:], init + [v]):
# replace with "yield from" on Python 3
yield ret
print(list(compositions([1, 2, 3])))
# So, in the first call, it will yield the empty list []
# and will iterate through [1, 2, 3, 4]
#
# In the first iteration (element 1), it will add the
# element to the list and call the function with the
# remaining elements:
#
# for ret in compositions([2, 3, 4], [1]):
#
# In this second call, it will yield the list with
# an single element [1] and will iterate through
# [2, 3, 4]
#
# In the first iteration (element 2), it will add the
# element to the list and call the function with the
# remaining elements:
#
# for ret in compositions([3, 4], [1, 2]):
#
# And so on...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment