I want to know how to write an algorithm that gives me all the possible combinations of a list of numbers with repetition & without using itertools in Python.
For example: all possible combinations of the list [1,2]
:
[[1,1],[1,2],[2,2],[2,1]]
All possible combinations of the list [1,2,3]
. The algorithm will then give me 27 (33) different lists in a list.
This was my code:
def all_possibilities(list):
result = [list]
for i in list:
new_list1 = list[:]
for k in range(len(list)):
new_list2 = list[:]
new_list1[k] = i
new_list2[k] = i
if new_list1 != list:
result.append(new_list1)
if new_list2 != list:
result.append(new_list2)
for u in result:
for y in result:
if u == y and (u is y) == False:
result.remove(y)
return (len(result),result)