I'm trying to create a set of test cases for a project I'm working on, and I'd like to create all possible test cases and iterate through them (quick program, shouldn't take long). The test cases should all be a list of length 1-4 and each item on the list should be an integer between 0-10, inclusive. The first item on the list should be 0. The set of lists would then be:
[0]
[0,0]
[0,1]
[0,2]
[0,3]
...
[0,10]
[0,0,0]
[0,0,1]
[0,0,2]
[0,0,3]
...
[0,1,0]
[0,1,1]
[0,1,2]
...
[0,10,10]
...
[0,10,10,10]
This is what I have so far, but it's not outputting the correct lists:
test_list = [0]
for length in range(2, 5):
while len(test_list) < length:
test_list.append(0)
for position in range(1, length):
for digit in range (0, 11):
test_list[position] = digit
print test_list
or you could generate the lists with a generator; this way you would not have the whole list in memory:
from itertools import product
def gen():
yield [0]
for i in range(11):
yield [0, i]
for i, j in product(range(11), range(11)):
yield [0, i, j]
for i, j, k in product(range(11), range(11), range(11)):
yield [0, i, j, k]
for item in gen():
print(item)
this seems pretty readable to me but is not extensible (in case you need longer lists) as other answers here.
therefore here the version where the length of the list is tweakable:
from itertools import product
def gen(length):
for l in range(length):
for tpl in product(range(11), repeat=l):
yield (0,) + tpl
for item in gen(length=4):
print(item)
this version now returns tuples
and not lists
. in case this matters you can surrout the return values with list()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With