Which itertools generator doesn't skip any combinations?

不想你离开。 提交于 2019-11-28 10:44:07

问题


When I run this code I don't get all the possible combinations of 3 characters:

def comb(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in permutations(range(n), r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)
def start():
    for x in comb("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;",3):
        print x

Instead it skips some. When I repeated the characters 3 times, I got all the combinations I needed, but I get some multiple times. This takes triple the time and isn't what I want. I'm going to be calculating millions of of combinations so I need to to know an alternative to repeating the characters.


回答1:


You're looking for itertools.product(characters, repeat = 3).

See the itertools.product docs.

>>> ' '.join(''.join(x) for x in itertools.product('abcd', repeat = 2))
aa ab ac ad ba bb bc bd ca cb cc cd da db dc dd


来源:https://stackoverflow.com/questions/10234599/which-itertools-generator-doesnt-skip-any-combinations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!