我正在使用Ruby实现一个递归的powerset算法,我遇到了this Stack Overflow帖子。
def powerset(set)
return [set] if set.empty?
p = set.pop
subset = powerset(set)
subset | subset.map { |x| x | [p] }
end
powerset(['a'], ['b'], ['c']) ---> [[], ["a"], ["b"], ["a", "b"], ["c"], ["a", "c"], ["b", "c"], ["a", "b", "c"]]
基本上,我在理解最后一行时感到茫然。我知道这是' bitwise or'操作员,我一般都明白这是做什么的,但是我很难理解它在最后一行中是如何工作的。
有人能告诉我更容易阅读Ruby的等价物吗?
答案 0 :(得分:1)
这里有一个易于阅读的单词:)
If the set is empty:
return a list with one empty set
Remove an element from the set and call it "p"
Call "subset" the powerset of the new set (that excludes p)
Return the union of this new powerset and another
version of it, where p is added to each of its sets