[PYTHON] The second night of the loop with for

http://d.hatena.ne.jp/shindannin/20111202/1322833089 Yes, tonight's reference is from the link above

Problem 1 Count FizzBuzz How many integers from A to B that are divisible by 3 or 5? With that Reprinting the example of the other party is confusing, so just for me

Brute force using for loop.py


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import io
import re
import math

####Memory usage and operating time check preparation
from guppy import hpy
import time
h = hpy()
start = time.clock()
####Up to here
i=0
j=0

#ex1
for x in range(5, 11):
    if x%3==0 or x%5==0:
        i+=1

#ex2
for y in range(14, 17):
    if y%3==0 or y%5==0:
        j+=1
            

print 'ex1:'+str(i),'ex2:'+str(j)
####Memory usage and operating time output
end = time.clock()
print h.heap()
print end-start

Is range (5,11) so intuitive to turn from 5 to 10 with for? I don't think it is, but I didn't like this when I wrote an integer between A and B in a while statement.

When written in a while statement.py


 i=0
a,b =5,10
#↓ will be specified to be executed between A and B
while a<=b:
#When it is divisible by 3 or 5, add 1 to the counter
   if a%3==0 or a%5==0:
     i+=1
#Add 1 by a before returning to the condition judgment of the execution of the while part.
   a+=1

Hmmm, I think for is better in this case. And next

Problem 2 Count FizzBuzz (2) x is an integer from 0 to X, y is an integer from 0 to Y, and z is an integer from 0 to Z. How many combinations of (x, y, z) are there in which x + y * y + z * z * z * z is divisible by 3 or 5?

Brute force using multiple for loops


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import io
import re
import math

####Memory usage and operating time check preparation
from guppy import hpy
import time
h = hpy()
start = time.clock()
####Up to here
i=0

for x in range(0,101):
    for y in range(0,101):
        for z in range(0,101):
            tmp=x + y*y + z*z*z*z
            if tmp%3==0 or tmp%5==0:
                i+=1
            else:
                pass

print i

            


####Memory usage and operating time output
end = time.clock()
print h.heap()
print end-start

For the time being, I wrote it while, but this is also not beautiful. .. .. And the execution speed was about 0.61 seconds for the for statement and 0.70 seconds for the while statement.

When using while.py


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import io
import re
import math

####Memory usage and operating time check preparation
from guppy import hpy
import time
h = hpy()
start = time.clock()
####Up to here
i=0
x=y=z=0

while x<=100:
    while y<=100:
        while z<=100:
            tmp=x + y*y + z*z*z*z
            if tmp%3==0 or tmp%5==0:
                i+=1
            else:
                pass
            z+=1
        y+=1
        z=0
    x+=1
    y=0
print i


####Memory usage and operating time output
end = time.clock()
print h.heap()
print end-start

I think I've seen somewhere that else: pass is unnecessary, useless, and shouldn't be written, but I often write it. .. .. Also, if you exit while once and then return in a loop again to execute the while statement that is a child, you can search for a method other than reassigning 0 to the counter at the exit. .. ..

from __future__ import print_function Will be incorporated from tomorrow.

That's all for tonight.

Recommended Posts

The second night of the loop with for
The third night of the loop with for
4th night of loop with for
Predict the second round of summer 2016 with scikit-learn
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.
Check the memory protection of linux kerne with the code for ARM
Aggregate the number of hits per second for one day from the web server log 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.
Get the key for the second layer migration of JSON data in python
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
Find the second derivative with JAX automatic differentiation
2016 The University of Tokyo Mathematics Solved with Python
[Note] Export the html of the site with python.
See the behavior of drunkenness with reinforcement learning
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
Use logger with Python for the time being
Watch out for the return value of __len__
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
I want to add silence to the beginning of a wav file for 1 second
Dump the contents of redis db with lua
Tucker decomposition of the hay process with HOOI
Put the second axis in 2dhistgram of matplotlib
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
Second half of the first day of studying Python Try hitting the Twitter API with Bottle
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
Extract the table of image files with OneDrive & Python
Coordinates of the right end of Label made with tkinter
The story of stopping the production service with the hostname command
Learn Nim with Python (from the beginning of the year).
Find the sum of unique values with pandas crosstab
Play with the UI implementation of Pythonista3 [Super Super Introduction]