I came across this function to return every combination of N values from an array:
def combs(a, n):
if n == 0:
return [[]]
else:
return [(x + [y]) for x in combs(a,n-1) for y in a]
For my own comprehension, I tried to convert it into a function using nested for loops:
def combinations(array,n):
if n == 0:
return [[]]
else:
for i in array:
for j in combinations(array, n-1):
return [j + [i]]
But I am getting different results than I am expecting.
>>> threes = ['aA','bB','cC']
>>>
>>> combs(threes,2)
[['aA', 'aA'], ['aA', 'bB'], ['aA', 'cC'], ['bB', 'aA'], ['bB', 'bB'], ['bB', 'cC'], ['cC', 'aA'], ['cC', 'bB'], ['cC', 'cC']]
>>>
>>> combinations(threes,2)
[['aA', 'aA']]
>>>
I've tried various versions of the line return [j+[i]] all with no success. Here are some examples:
return (j + [i])
Traceback (most recent call last):
File "...", line 24, in <module>
print(combinations(threes,2))
File "...", line 16, in combinations
return (j + [i])
TypeError: can only concatenate str (not "list") to str
.
return j + [i]
Traceback (most recent call last):
File "...", line 24, in <module>
print(combinations(threes,2))
File "...", line 16, in combinations
return j + [i]
TypeError: can only concatenate str (not "list") to str
Why is the first function's list comprehension returning something different then my expanded nested for loops version?
What would be the correct (functioning) method to convert the first function's list-comprehension and return value into the nested for loop strategy?