Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a Python list with every combination of '+', '-', '*', and '/' strings

I am trying to build a 2d list of test cases that contains all the possible cases (‘+’, ‘-‘, ‘*’, ‘/’) like this:

[['+', '+', '+', '+'],
 ['+', '+', '+', '-'],
 ['+', '+', '-', '-'],
......
['/', '/', '/', '/']]

I am thinking to create it in a Python list comprehension. I tried:

[[x] * 4 for x in ('+','-','*', '/')]

but the result is not something I want. Anyone knows how to do it? Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

itertools.combinations_with_replacement?

In [1]: from itertools import combinations_with_replacement
In [2]: list(combinations_with_replacement(["+", "-", "/", "*"], 4))
Out[2]:
[('+', '+', '+', '+'),
 ('+', '+', '+', '-'),
 ('+', '+', '+', '/'),
 ('+', '+', '+', '*'),
 ('+', '+', '-', '-'),
 ('+', '+', '-', '/'),
 ('+', '+', '-', '*'),
 ('+', '+', '/', '/'),
 ('+', '+', '/', '*'),
 ('+', '+', '*', '*'),
 ('+', '-', '-', '-'),
 ('+', '-', '-', '/'),
 ('+', '-', '-', '*'),
 ('+', '-', '/', '/'),
 ('+', '-', '/', '*'),
 ('+', '-', '*', '*'),
 ('+', '/', '/', '/'),
 ('+', '/', '/', '*'),
 ('+', '/', '*', '*'),
 ('+', '*', '*', '*'),
 ('-', '-', '-', '-'),
 ('-', '-', '-', '/'),
 ('-', '-', '-', '*'),
 ('-', '-', '/', '/'),
 ('-', '-', '/', '*'),
 ('-', '-', '*', '*'),
 ('-', '/', '/', '/'),
 ('-', '/', '/', '*'),
 ('-', '/', '*', '*'),
 ('-', '*', '*', '*'),
 ('/', '/', '/', '/'),
 ('/', '/', '/', '*'),
 ('/', '/', '*', '*'),
 ('/', '*', '*', '*'),
 ('*', '*', '*', '*')]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading