列表的顺序子集

时间:2012-01-14 10:07:23

标签: wolfram-mathematica

给出一个列表

{"a", "b", "c", "d"}

是否有更简单的方法来生成这样的顺序子集列表(结果的顺序并不重要)

{
 {"a"},
 {"a b"},
 {"a b c"},
 {"a b c d"},
 {"b"},
 {"b c"},
 {"b c d"},
 {"c"},
 {"c d"},
 {"d"}
}

7 个答案:

答案 0 :(得分:19)

我想我最喜欢这个:

set = {"a", "b", "c", "d"};

ReplaceList[set, {___, x__, ___} :> {x}]

加入字符串:

ReplaceList[set, {___, x__, ___} :> "" <> Riffle[{x}, " "]]

以类似的方式,特定于字符串:

StringCases["abcd", __, Overlaps -> All]

由于纳赛尔说我在作弊,所以这是一种更加手动的方法,在大型套装上也有更高的效率:

ClearAll[f, f2]
f[i_][x_] := NestList[i, x, Length@x - 1]
f2[set_]  := Join @@ ( f[Most] /@ f[Rest][set] )

f2[{"a", "b", "c", "d"}]

答案 1 :(得分:14)

Flatten[Partition[{a, b, c, d}, #, 1] & /@ {1, 2, 3, 4}, 1]

给出

  

{{a},{b},{c},{d},{a,b},{b,c},{c,d},{a,b,c},{b,c ,d},{a,   b,c,d}}

答案 2 :(得分:7)

这个怎么样:

origset = {"a", "b", "c", "d"};

bdidxset = Subsets[Range[4], {1, 2}]

origset[[#[[1]] ;; #[[-1]]]] & /@ bdidxset

给出了

{{"a"}, {"b"}, {"c"}, {"d"}, {"a", "b"}, {"a", "b", "c"}, {"a", "b", 
  "c", "d"}, {"b", "c"}, {"b", "c", "d"}, {"c", "d"}}

答案 3 :(得分:5)

我更喜欢TomD的方法,但这就是我想到的,没有字符串处理:

set = {"a", "b", "c", "d"};

n = Length@set;

Join @@ Table[set~Take~{s, f}, {s, n}, {f, s, n}] // Column

Mathematica graphics

答案 4 :(得分:1)

你可以这样做:

a = {"a", "b", "c", "d"};
b = List[StringJoin[Riffle[#, " "]]] & /@
  Flatten[Table[c = Drop[a, n];
    Table[Take[c, i], {i, Length[c]}],
    {n, 0, Length[a]}], 1]

输出将如下所示:

{{"a"}, {"a b"}, {"a b c"}, {"a b c d"}, {"b"}, {"b c"}, {"b c d"}, {"c"}, {"c d"}, {"d"}}

答案 5 :(得分:1)

这是一种可能的解决方案

a={"a","b","c","d"};
StringJoin@Riffle[#, " "] & /@ 
  DeleteDuplicates[
   LongestCommonSubsequence[a, #] & /@ 
    DeleteCases[Subsets@a, {}]] // Column

结果

a
b
c
d
a b
b c
c d
a b c
b c d
a b c d

答案 6 :(得分:1)

单步:

makeList[lst_] := Map[ Union[lst[[1 ;; #]]] &, Range@Length[lst]]
r = Map[makeList[lst[[# ;; -1]]] &, Range@Length[lst]];
Flatten[r, 1]

给出

{{"a"}, 
 {"a", "b"}, 
 {"a", "b", "c"}, 
 {"a", "b", "c", "d"}, 
 {"b"},
 {"b", "c"},
 {"b", "c", "d"},
 {"c"}, 
 {"c", "d"}, 
 {"d"}}