首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

递归求所有子集

2012-09-08 
递归求全部子集Complete the definition of a function subsets that returns a list of allsubsets of a

递归求全部子集
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

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

热点排行