[PYTHON] The third night of the loop with for

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

The third night of the loop with for
The second night of the loop with for
4th night of loop with for
Add the attribute of the object of the class with the for statement
[For beginners] Quantify the similarity of sentences with TF-IDF
The story of making a standard driver for db with python.
Ask for Pi with the bc command
Align the size of the colorbar with matplotlib
Search for files with the specified extension
Check the existence of the file with python
Pandas of the beginner, by the beginner, for the beginner [Python]
Count the number of characters with echo
Trial to judge the timing of the progress display of the for loop using 0b1111 ~
I measured the speed of list comprehension, for and while with python2.7.
The story of doing deep learning with TPU
Note: Prepare the environment of CmdStanPy with docker
The story of low learning costs for Python
Prepare the execution environment of Python3 with Docker
2016 The University of Tokyo Mathematics Solved with Python
[Note] Export the html of the site with python.
Exposing the DCGAN model for Cifar 10 with keras
Increase the font size of the graph with matplotlib
Calculate the total number of combinations with python
Watch out for the return value of __len__
Check the date of the flag duty with Python
I played with Floydhub for the time being
Eliminate the inconveniences of QDock Widget with PySide
Challenge the Tower of Hanoi with recursion + stack
Image processing? The story of starting Python for
Rewrite the name of the namespaced tag with lxml
Fill the browser with the width of Jupyter Notebook
Predict the second round of summer 2016 with scikit-learn
Dump the contents of redis db with lua
Tucker decomposition of the hay process with HOOI
Find out the day of the week with datetime
The basis of graph theory with matplotlib animation
Code for checking the operation of Python Matplotlib
Checklist on how to avoid turning the elements of numpy's array with for
Visualize the behavior of the sorting algorithm with matplotlib
Convert the character code of the file with Python3
Align the number of samples between classes of data for machine learning with Python
[Python] Determine the type of iris with SVM
[Introduction to Python] How to get the index of data with a for statement
The first step of machine learning ~ For those who want to implement with python ~
Build API server for checking the operation of front implementation with python3 and Flask
Save the output of conditional GAN for each class ~ With cGAN implementation by PyTorch ~
See here for the amount of free memory of the free command
Coordinates of the right end of Label made with tkinter
The story of stopping the production service with the hostname command
Find the sum of unique values with pandas crosstab
Play with the UI implementation of Pythonista3 [Super Super Introduction]
The story of replacing Nvidia GTX 1650 with Linux Mint 20.1.
Add information to the bottom of the figure with Matplotlib
I tried the MNIST tutorial for beginners of tensorflow.
Get the sum of each of multiple columns with awk
Run with CentOS7 + Apache2.4 + Python3.6 for the time being
The story of sharing the pyenv environment with multiple users
Destroy the intermediate expression of the sweep method with Python
Take a screenshot of the LCD with Python-LEGO Mindstorms
Summary of tools for operating Windows GUI with Python
Display the integrated temperature for each field with Z-GIS