+ -
当前位置:首页 → 问答吧 → 递归求全部子集

递归求全部子集

时间:2011-11-25

来源:互联网

Complete the definition of a function subsets that returns a list of all
subsets of a set s. Each subset should itself be a set. The solution can be
expressed in a single line (although a multi-line solution is fine)."""

def subsets(s):
  """Return a list of the subsets of s.

  >>> subsets({True, False})
  [{False, True}, {False}, {True}, set()]
  >>> counts = {x for x in range(10)} # A set comprehension
  >>> subs = subsets(counts)
  >>> len(subs)
  1024
  >>> counts in subs
  True
  >>> len(counts)
  10
  """
  assert type(s) == set, str(s) + ' is not a set.'
  if not s:
  return [set()]
  element = s.pop() # Remove an element
  rest = subsets(s) # Find all subsets of the remaining elements
  s.add(element) # Add the element back, so that s is unchanged
  # code here #

递归真的把我搞晕了。。。满足doctest

作者: yuyuyu101   发布时间: 2011-11-25

参考itertools模块里的组合函数,里面有对应的普通写法,用循环+yield来做,不是递归...

作者: angel_su   发布时间: 2011-11-25