Reputation: 119
I want to create a function in python that as input takes a list with an unspecified amount of strings whose length is also not standard or the same with each other. The input would be like this:
list = ['1234', '4', '97', ... , '542']
The first element of this list represents all the possible numbers that could be the first digit of a number, the second element the possible numbers that could be the second digit and so on. As output, I want to have a list with all the possible numbers that could be generated this way. Here is an example:
input = ['12', '45', '865']
output = ['148', '146', '145', '158', '156', '155',
'248', '246', '245', '258', '256', '255']
Is there an algorithm for this? I am not completely new to python but this problem has me at a loss. Thanks for any help.
Upvotes: 0
Views: 68
Reputation: 1478
Tested with Python 2.7
Input = ['12', '45', '865']
out = [[]]
# algo
for liste in Input:
out = [x + [y] for x in out for y in liste]
#print out # un comment to see how algo works
index = 0
while index < len(out):
out[index] = ''.join(out[index])
index += 1
print out
# prodcues:
# ['148', '146', '145', '158', '156', '155',
# '248', '246', '245', '258', '256', '255']
# The while loop can be reduced to:
# print [''.join(liste) for liste in out]
Upvotes: 1
Reputation: 24288
from itertools import product
input = ['12', '45', '865']
[''.join(prod) for prod in product(*input)]
# ['148', '146', '145', '158', '156', '155', '248', '246',
# '245', '258', '256', '255']
itertools.product takes a number of iterables as parameters, and yields their cartesian product.
As your iterables (your strings) are in a list, we use the *input syntax to unpack the elements of the list to separate positional parameters.
Upvotes: 4