简体   繁体   中英

Python ordered combination of numbers?

I am looking to write something that will display an ordered list of all possible combinations. It can start at something like

11-AA 11-AB 11-AC

...and eventually end at...

59-YZ 59-ZZ

I would also like it if the first part of the number can only be between 1-5. I have been working with itertools, but I am having a hard time generating this specific sort of thing. I can generate all possible combinations of 4 letters repeated twice, but I'm having issues getting the dash in, and telling the program that "Hey, you can only chose between 1 and 4 for the first number".

import itertools

perms = itertools.product('ABCD', repeat=2)

for perm in perms:
    print('The possible combinations are', perm)

There is the code for that. This doesn't HAVE to use itertools, that is just what I was familar with.

EDIT: The first answer was precisely what I needed. I didn't like what the itertools was doing because of the commas, but the little snippet you showed me is magic. Thank you.

To answer the question, a loop just seemed less clean? I also just discovered the itertools, and am probably enjoying it too much.

Just do this in equal pieces. One character has to be 1 , 2 , 3 , 4 , or 5 ; the second can be any digit; the third must be - , the last two must be A , B , C , or D , so:

perms = itertools.product('12345', '0123456789', '-', 'ABCD', 'ABCD')

And then, to join them up into strings:

print('The possible combinations are:')
for perm in perms:
    print(''.join(perm))

This starts with 10-AA , not 11-AA . There's no way to end with 59 if you start with 11 (assuming you want the numbers in order).


I originally left the - out and joined up each string with format , but I think this is slower. It's also at least twice as fast on every Python version I have handy. (The cost of a 1-length loop in C is trivial, as is building a 5-tuple vs. a 4-tuple; the cost of format vs. join is not.)

You could also product up a range(11, 60) and a product('ABCD', repeat=2) , then flatten it with chain , then format each one. While that's conceptually simpler, it's going to be a lot harder to read, and is about as slow as the flat format version.

Anyway, in 64-bit python.org 3.3.2 on OS X 10.9:

In [1189]: %timeit collections.deque((''.join(perm) for perm in itertools.product('1234', '1234567890', '-', 'ABCD', 'ABCD')), maxlen=0)
10000 loops, best of 3: 129 µs per loop

In [1190]: %timeit collections.deque(('{}{}-{}{}'.format(*perm) for perm in itertools.product('1234', '1234567890', 'ABCD', 'ABCD')), maxlen=0)
1000 loops, best of 3: 359 µs per loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM