Variable number of predictable for loops in Python

后端 未结 2 1830

I am trying to come up with a way to generate all possible unique strings from an alphabet of 20 characters where the order within the string doesn\'t matter, and the length

相关标签:
2条回答
  • 2020-12-21 01:16
    1. the code for itertools.product does exactly what you want and is much more efficient that nested loops

    2. i suspect that what you really want is itertools.combinations_with_replacement

    0 讨论(0)
  • 2020-12-21 01:18

    IIUC, you can simply use itertools.combinations_with_replacement.

    >>> list(map(''.join, combinations_with_replacement(["a","b","c"],2)))
    ['aa', 'ab', 'ac', 'bb', 'bc', 'cc']
    >>> list(map(''.join, combinations_with_replacement(["a","b","c"],3)))
    ['aaa', 'aab', 'aac', 'abb', 'abc', 'acc', 'bbb', 'bbc', 'bcc', 'ccc']
    >>> list(map(''.join, combinations_with_replacement(alphabet,4))) == orig(alphabet)
    True
    

    (where orig is simply your original code wrapped into a function).

    0 讨论(0)
提交回复
热议问题