I tried to refactor the code of Python beginner (junior high school student)

A Python program written by a junior high school student. It was well done for the first time. At first, you can use any writing style. I think.

However, in order to be able to create difficult programs, it is important to organize your mind and make the program easy to understand. I rewrote this program as an example.

Original program

I was able to draw beautiful figures. It is wonderful to devise a way to put out colorful shades. I made it by carefully considering the conditional division of the if statement and the calculation formula.

number = int(input("How many circles do you draw?"))
R = 1.0
G = 0.0
B = 0.0
color = 0
from turtle import *
delay(5)
shape("turtle")
for i in range(number):
    color = int(360/number*i)
    if color <= 60:
        R = 1.0
        G = color/60
        B = 0.0
    elif color <= 120:
        R = 2.0-color/60
        G = 1.0
        B = 0.0
    elif color <= 180:
        R = 0.0
        G = 1.0
        B = color/60-2.0
    elif color <= 240:
        R = 0.0
        G = 4.0-color/60
        B = 1.0
    elif color <= 300:
        R = color/60-4.0
        G = 0.0
        B = 1.0
    elif color <= 360:
        R = 1.0
        G = 0.0
        B = 6.0-color/60

    pencolor(R,G,B)
    circle(100)
    left(360/number)
done()

Execution result lessen_turtle.png

Start cooking

import moves first The part for finding the RGB value is functionalized I can't see the regularity of the formula in the if statement. I think it was made by trial and error. Changed to a regular expression with the same result. = Is included in the conditional expression of the if statement, but the result does not change even if = is excluded. color Considering that the range is 0 to 359, it seems more appropriate to not add =.

import turtle

def color2rgb(color):
    if color < 60:
        R = 1.0
        G = color/60
        B = 0.0
    elif color < 120:
        R = 1.0-(color-60)/60
        G = 1.0
        B = 0.0
    elif color < 180:
        R = 0.0
        G = 1.0
        B = (color-120)/60
    elif color < 240:
        R = 0.0
        G = 1.0-(color-180)/60
        B = 1.0
    elif color < 300:
        R = (color-240)/60
        G = 0.0
        B = 1.0
    elif color < 360:
        R = 1.0
        G = 0.0
        B = 1.0-(color-300)/60
    return(R, G, B)

def draw(number):
    turtle.delay(5)
    turtle.shape("turtle")
    for i in range(number):
        color = int(360 / number * i)
        turtle.pencolor(color2rgb(color))
        turtle.circle(100)
        turtle.left(360 / number)
    turtle.done()

number = int(input("How many circles do you draw?"))
draw(number)

further

If you look closely at color2rgb (), the values of R, G, and B have the same shape with a phase shift of 120. You can also stop the if statement and create a table. However, if you make it into a table, the readability will decrease a little. Let's do this.

import turtle

def color2r(color):
    color = color % 360
    if color < 60:
        R = 1.0
    elif color < 120:
        R = 1.0-(color-60)/60
    elif color < 180:
        R = 0.0
    elif color < 240:
        R = 0.0
    elif color < 300:
        R = (color-240)/60
    elif color < 360:
        R = 1.0
    return R

def color2rgb(color):
    return color2r(color), color2r(color-120), color2r(color-240)

def draw(number):
    turtle.delay(5)
    turtle.shape("turtle")
    for i in range(number):
        color = int(360 / number * i)
        turtle.pencolor(color2rgb(color))
        turtle.circle(100)
        turtle.left(360 / number)
    turtle.done()

number = int(input("How many circles do you draw?"))
draw(number)

Extra edition

Looking at the comments I received, the image swelled, so I made a function table version. I don't know if it's easy to read, but I like it.

import turtle

convert_func_table = [lambda x: 1.0, lambda x:1.0-x/60, lambda x:0, lambda x:0, lambda x:x/60, lambda x:1.0]

def convert(i,fine):
    return convert_func_table[i%6](fine)

def color2rgb(color):
    i, fine = divmod(color, 60)
    return (
        convert(i, fine),
        convert(i+4, fine),
        convert(i+2, fine),
    )

def draw(number):
    turtle.delay(5)
    turtle.shape("turtle")
    for i in range(number):
        color = int(360/number*i)
        turtle.pencolor(color2rgb(color))
        turtle.circle(100)
        turtle.left(360/number)
    turtle.done()

number = int(input("How many circles do you draw?"))
draw(number)

Thank you, Mr. K, for providing the program.

Recommended Posts

I tried to refactor the code of Python beginner (junior high school student)
I tried to get the authentication code of Qiita API with Python.
I tried to summarize the string operations of Python
[Python] A junior high school student implemented Perceptron and tried to classify irises.
Programming beginner (junior high school student) Optimize the created algorithm
I tried to find the entropy of the image with python
[Python] I tried to visualize the follow relationship of Twitter
I wrote the code to write the code of Brainf * ck in python
From zero knowledge of Python to making AI in the first grade of junior high school
I tried to improve the efficiency of daily work with Python
(Python) I tried to analyze 1 million hands ~ I tried to estimate the number of AA ~
I tried to verify and analyze the acceleration of Python by Cython
I tried to streamline the standard role of new employees with Python
I tried to get the movie information of TMDb API with Python
I tried to touch the API of ebay
I tried to correct the keystone of the image
I tried to predict the price of ETF
I tried to vectorize the lyrics of Hinatazaka46!
I tried to refactor the template code posted in "Getting images from Flickr API with Python" (Part 2)
[Python] I tried to judge the member image of the idol group using Keras
I tried to easily visualize the tweets of JAWS DAYS 2017 with Python + ELK
I tried to automate the 100 yen deposit of Rakuten horse racing (python / selenium)
I tried to automatically send the literature of the new coronavirus to LINE with Python
python beginners tried to predict the number of criminals
I tried to graph the packages installed in Python
I tried to summarize how to use matplotlib of python
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to visualize the spacha information of VTuber
I tried to erase the negative part of Meros
I tried to solve the problem with Python Vol.1
I felt that I ported the Python code to C ++ 98.
[Python] I tried to get Json of squid ring 2
I tried to classify the voices of voice actors
I tried running the sample code of the Ansible module
I tried to put out the frequent word ranking of LINE talk with Python
Python practice 100 knocks I tried to visualize the decision tree of Chapter 5 using graphviz
mong --I tried porting the code that randomly generates Docker container names to Python -
Python beginner (junior high school student) combination generation was diagonally above (combination generation by recursive processing)
I tried to compare the processing speed with dplyr of R and pandas of Python
The 15th offline real-time I tried to solve the problem of how to write with python
[Horse Racing] I tried to quantify the strength of racehorses
I tried "gamma correction" of the image with Python + OpenCV
I tried to simulate how the infection spreads with Python
I tried the accuracy of three Stirling's approximations in python
I tried to find the average of the sequence with TensorFlow
I tried to summarize the code often used in Pandas
I tried to implement the mail sending function in Python
[Machine learning] I tried to summarize the theory of Adaboost
[Python] I tried collecting data using the API of wikipedia
I tried to enumerate the differences between java and python
I tried to fight the Local Minimum of Goldstein-Price Function
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
I tried to divide the file into folders with Python
I tried to implement blackjack of card game in Python
How to write offline real time I tried to solve the problem of F02 with Python
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I tried to create a Python script to get the value of a cell in Microsoft Excel
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I tried to touch Python (installation)