Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

python - Which itertools generator doesn't skip any combinations?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...