Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort itertools.product in Python?

Tags:

python

This is Product from itertools:

product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy

But I wanna change to: --> Ax Bx Cx Dx Ay By Cy Dy How can I do that?

like image 630
Markup2510 Avatar asked Oct 23 '25 18:10

Markup2510


2 Answers

Change the order of arguments and reverse tuples product yields. It'll probably be more efficient than sorting, since it doesn't need to build intermediate list.

from itertools import product

def reorder_product(*a):
    for tup in product(*a[::-1]):
        yield tup[::-1]

Example:

print(*[''.join(t) for t in reorder_product('ABCD', 'xy')])
# Output:
#     Ax Bx Cx Dx Ay By Cy Dy
like image 64
vaultah Avatar answered Oct 26 '25 07:10

vaultah


You'll probably be most efficient if you swap the order of the product and then simply reverse each of the yielded items:

def product_sorted_by_second(first, second):
    for item in itertools.product(second, first):
        yield item[::-1]

Of course, this is a horrible name for the function (since we aren't really sorting).

The advantage here is that you don't actually need to sort (which is an O(NlogN) processing step). So this ends up being an O(N) algorithm (where N is len(first) * len(second))

like image 43
mgilson Avatar answered Oct 26 '25 06:10

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!