PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

[FIXED] How to generate itertools product without duplicates?

 May 09, 2022     itertools, product, python     No comments   

Issue

I think i list a bad example, i apologize for this, have reedited this with another example, please see this version.

i know there is a very similar question: Itertools product without repeating duplicates

but i have something different.For example:

a = ['add', 'sub']
b = [2,3, 'a', 'b']
c = [1,3, 'a', 'c']
list(it.product(a, b, c))  # result is:[('add', 2, 1),('add', 2, 3),('add', 2, 'a'), ('add', 2, 'c'),
#('add', 3, 1),('add', 3, 3),('add', 3, 'a'),('add', 3, 'c'),('add', 'a', 1),('add', 'a', 3),
#('add', 'a', 'a'),('add', 'a', 'c'), ('add', 'b', 1),('add', 'b', 3),('add', 'b', 'a'),
#('add', 'b', 'c'),('sub', 2, 1),('sub', 2, 3),('sub', 2, 'a'),('sub', 2, 'c'),('sub', 3, 1),
#('sub', 3, 3),('sub', 3, 'a'),('sub', 3, 'c'),('sub', 'a', 1),('sub', 'a', 3),('sub', 'a', 'a'),
#('sub', 'a', 'c'),('sub', 'b', 1),('sub', 'b', 3),('sub', 'b', 'a'),('sub', 'b', 'c')]

for the result:

I dont want add(a,a), as the first value == second value

i want to keep only 1 of add(3,a) add(a,3), as it is symmetric.

and my example only contains two list, but i may use 5 or more list to generate product.

i cant use cominations, because:

product(['add', 'sub', 1,2,3, 'a','b', 'c'], repeat=3) is different with product(['add', 'sub'], [2,3, 'a', 'b'], [1,3, 'a', 'c'])

something in product(['add', 'sub', 1,2,3, 'a','b', 'c'], repeat=3) is not ok for me.

i want a fast method, since my program is time sensitive.

Can anyone help on this?


Solution

You can take the implementation of itertools.product, tweak it so it matches your requirement:

def product_without_dupl(*args, repeat=1):
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool if y not in x] # here we added condition
    result = set(list(map(lambda x: tuple(sorted(x)), result))) # to remove symmetric duplicates
    for prod in result:
        yield tuple(prod)

Source: https://docs.python.org/3/library/itertools.html#itertools.product

Then the result:

a = [1,2,3]
b = [2,3,4]

for el in product_without_dupl(a,b):
    print(el)

#outputs:
(2, 4)
(1, 2)
(3, 4)
(1, 4)
(2, 3)
(1, 3)


Answered By - Grzegorz Skibinski
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing