Find the algorithm to write out all the patterns of the small set extracted from the set of 5 I referred to here.
(Addition) There is a convenient library, so let's use it. Thank you for telling me.
from itertools import combinations
list(combinations([1,2,4,3],3))
>>[(1, 2, 4), (1, 2, 3), (1, 4, 3), (2, 4, 3)]
The language used is python.
All patterns to take out 2 to 3 (if it does not disappear even if taken out)
Create a function called "choice" that extracts one from the whole set. If you take out one with "choice", increase the depth by one and call "choice" again. When the depth reaches the number to be taken out, it will come back. Now you can generate all the patterns.
If you want to take it out and disappear, you can execute "choice" and pass the whole set excluding the selected one to the next "choice".
One problem is that this is There is a problem that the same patterns of [red, green] and [green, red] are mixed. There is no help for it here, so check if there is the same element, and if there is, delete one. Please let me know if there is a better way.
import copy
class Allpattern():
def __init__(self,n,r):
self.n = n #n Of these, r all patterns to take out
self.r = r
self.pattern = []
used = [0] * self.n
hoge =[]
for i in range(r):
hoge.append(used)
def make(self):
"""
list1 = [1 ,・ ・ ・ ・, n]Make the whole set
"""
list1=[]
for i in range(self.n):
list1.append(i+1)
"""
choice_list: A list to put the choices
depth :Number of choices
"""
choice_list = []
depth = 0
self.choice(list1,depth,choice_list)
def choice(self,list1,depth,choice_list):
for i in list1:
list2 = copy.deepcopy(list1)
list2.remove(i) #Choose once and never choose again
choice_list2 = copy.deepcopy(choice_list)
choice_list2.append(i)
if depth+1 >= self.r:
self.work(choice_list2)
else:
self.choice(list2,depth+1,choice_list2)
def work(self,choice_list):
"""
It is called when the selection of r is completed.
"""
choice_list.sort()
if self.pattern.count(choice_list) == 0:
self.pattern.append(choice_list)
def disp(self):
for i in self.pattern:
print(i)
if __name__ == '__main__' :
hoge = Allpattern(5,3)
hoge.make()
hoge.disp()
Execution result
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
Recommended Posts