代码之家  ›  专栏  ›  技术社区  ›  Matt W

如何在给定值列表时生成字符串的所有可能组合

  •  1
  • Matt W  · 技术社区  · 14 年前

    "100","200","300","400","500", ...
    

    我有一个模板字符串,其中有一些需要替换的标记:

    "@token1@-@token2@-@token3@-....-@tokenN@"
    

    使用值列表,如何在模板中生成所有可能的值组合?

    3 回复  |  直到 11 年前
        1
  •  2
  •   mvds    14 年前

    利用递归,只是为了好玩:

    r($values,false,$numtokens); // false to get 100-100-100 as well.
    
    function r($values,$unique=true,$depth=3,$collect=array())
    {
        if ( $depth == 0 )
        {
                print implode("-",$collect)."\n";
        } else {
                foreach ( $values as $id=>$t )
                {
                        if ( $unique ) unset($values[$id]);
                        r($values,$unique,$depth-1,array_merge($collect,array($t)));
                        if ( $unique ) $values[$id] = $t;
                }
        }
    }
    

        2
  •  1
  •   Kevin Stock    14 年前

    from itertools import permutations
    list_of_values = ["100","200","300","400","500"]
    template = "%s-%s-%s"
    for p in permutations(list_of_values,3):
      print(template % p)
    

    如果不想以“500-400-300”和“300-400-500”为例,可以用组合代替排列。

        3
  •  0
  •   Douglas Leeder    14 年前

    假设值可以重复:

    #!/usr/bin/env python
    
    VALUES=['100','200','300','400','500']
    
    TOKEN='@token%d@'
    
    TARGET="@token1@-@token2@-@token3@"
    
    def rep(n,target):
        src=TOKEN%n
        if src not in target:
            return [target]
    
        ret = []
        for v in VALUES:
            ret += rep(n+1, target.replace(src,v))
        return ret
    
    print rep(1,TARGET)