Yes, continue from yesterday [http://d.hatena.ne.jp/shindannin/20111202/1322833089] (http://d.hatena.ne.jp/shindannin/20111202/1322833089) Than.
Brute force with bits
There are 7 colors (red, orange, yellow, green, blue, indigo, purple). I chose three of them and decided to draw a picture. How many ways are there to choose paints?
When making a 7-fold loop with for.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import print_function
import sys
import io
import re
import math
cou = 0 #Counter with several colors of paint you just selected
res = 0 #When a combination of 3 colors comes out+1 Variable
#for color in range(2):In the first lap of the loop, 0 is assigned, so the color that is not used
#The second lap is the color I'm using.
for aka in range(2):
    for daidai in range(2):
        for ki in range(2):
            for midori in range(2):
                for ao in range(2):
                    for ai in range(2):
                        for murasaki in range(2):
#If you add each color at the deepest part of the loop and it is equal to 3, you can choose 3 colors.
                            cou=aka+daidai+ki+midori+ao+ai+murasaki
                            if cou==3:
                                res+=1
print (res)
If the conditions become complicated, it is not possible to deal with mistakes in writing or when the number of colors given increases, so there seems to be a method called for loop using bits. The following is a complete copy (although it is ambiguous whether it is made)
Brute force using bit.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import print_function
import sys
import io
import re
import math
max_colors = 7
result = 0
for all_color in range(1 << max_colors):
    num_colors = 0
    for color in range(max_colors):
        if (all_color & (1 << color)):
            num_colors += 1
    if num_colors == 3:
        result += 1
print (result, end='\n')
It's very likely that I'll make a mistake if I explain it without understanding it, so I'll omit the explanation tonight. print started with from future import print_function.
Recommended Posts