【问题标题】:Python itertools combinations lengthPython itertools 组合长度
【发布时间】:2017-11-10 21:02:16
【问题描述】:

希望您能提供有关此练习问题的任何意见:

给定一个长度为n 的字符串和一个整数k,在1 k n 的约束下打印所有可能的长度k 组合(打印nCk)。你可以假设没有重复的字符

例子:

abc, 2 --> ab, bc, ca

abc, 1 --> a, b, c

abc, 3 --> abc

【问题讨论】:

    标签: python combinations itertools


    【解决方案1】:
    import itertools
    
    def func(data, r):
        return ["".join(x) for x in itertools.combinations(data, r)]
    

    【讨论】:

    • 一些解释会有所帮助。
    • 谢谢雨。我明白你的回答,效果很好。
    【解决方案2】:

    感谢Rain的回答,效果很好。

    答案:

    import itertools
    
    def func(data, r):
        return ["".join(x) for x in itertools.combinations(data, r)]
    
    print(func('abc', 2))
    print(func('abc', 1))
    print(func('abc', 3))
    

    输出:

    ['ab', 'ac', 'bc']
    ['a', 'b', 'c']
    ['abc']
    

    注意事项:

    itertools.combinations(iterable, r)

    从输入迭代中返回 r 个长度的元素子序列。

    组合按字典排序顺序发出。因此,如果输入的可迭代对象是排序的,则组合元组将按排序顺序生成

    【讨论】:

      猜你喜欢
      • 2022-09-28
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2019-01-07
      相关资源
      最近更新 更多