I want to write in Python! (1) Code format check

Nice to meet you. This is leo1109, an engineer. Since this is my first post, I will write about Python, which I have been touching recently.

All the code used in the article has been uploaded on GitHub.

The story to introduce this time

Code format check. Click here for PyPI.

I want to write code in Python!

Today, I want to write a program in Python to get the Fibonacci number! So I will write it. The Fibonacci number is a sequence in which the terms in the sequence are the sum of the terms one before and two before.

Expressed in a mathematical formula, it looks like this:

n > 0, n is unsigned Int.
n = 1: F(1) = 1
n = 2: F(2) = 1
n > 2: F(n) = F(n-1) + F(n-2)

Let's write it immediately. We need to keep the previous value, so let's implement it using an array.

# python 3.5.2

def get_fibonacci_by_index(index):
    if index in [1 ,2]:
        return 1
    fibs =  [1, 1]

    for i in range(3, index + 1):
        c = fibs[i - 2] + fibs[i-3]
        fibs.append(c)

    return fibs[-1]

It's done!

Let's check the operation

I will check if it is working properly.

Python 3.5.2 (default, Dec 19 2016, 00:08:16)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import my_math
>>> x=[]
>>> for i in range(1, 11):
...     x.append(my_math.get_fibonacci_by_index(i))
...
>>> x
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

It seems to be working properly.

--Reference: https://ja.wikipedia.org/wiki/%E3%83%95%E3%82%A3%E3%83%9C%E3%83%8A%E3%83%83%E3%83% 81% E6% 95% B0

I'm curious

However, there are some subtleties to this code. For example, the following. Well, I'm curious.

def get_fibonacci_by_index(index):
    if index in [1,2]:
        return 1
    fibs =  [1, 1]  #Two spaces after equal?
...
        c = fibs[i - 2] + fibs[i-3]  # i-2 and i-3 is not unified

Python has a coding convention called PEP8.

Of course, it is good to write according to this, but it is difficult to write while checking whether this is followed every time. It is also very inefficient to have multiple people developing and writing differently for one person and messing up. That's where the code check tool flake8 comes in. I will leave the detailed explanation to other articles, but let's actually use it.

$ flake8 my_math_before.py
my_math_before.py:3:1: E302 expected 2 blank lines, found 1
my_math_before.py:4:19: E231 missing whitespace after ','
my_math_before.py:6:11: E222 multiple spaces after operator

Gununu. I was angry. I generally say the following.

Let's fix

It's easy to fix because it has the number of lines and the reason.

The diff looks like this.

3d2
< 
7,8c6
< 
<     fibs = [1, 1]
---
>     fibs =  [1, 1]
11c9
<         c = fibs[i-2] + fibs[i-3]
---
>         c = fibs[i - 2] + fibs[i-3]

Here is after the correction.

# python 3.5.2


def get_fibonacci_by_index(index):
    if index in [1, 2]:
        return 1

    fibs = [1, 1]

    for i in range(3, index + 1):
        c = fibs[i-2] + fibs[i-3]
        fibs.append(c)

    return fibs[-1]

Let's try flake8 again. If you specify a file name, you can check only the target file. If not specified, it seems to recursively look under the executed directory.

$ flake8 my_math.py

Nothing was displayed! this is convenient. By incorporating it in Jenkins build jobs etc., it seems that not only logic but also code uniformity can be guaranteed.

Summary

Frequent code checking improves visibility and reduces the chance of bugs being embedded. I've omitted a detailed introduction, but it will notify you of errors as well as formats.

# a.py
x = 2
x = z + 3
x = 5
 if x == 5:
  y = 5

$ flake8 a.py
a.py:5:1: E999 IndentationError: unexpected indent
a.py:5:2: E111 indentation is not a multiple of four
a.py:5:2: E113 unexpected indentation
a.py:6:3: E111 indentation is not a multiple of four

next time

I want to write the test of the Fibonacci number function I wrote this time in Python!

Postscript

Fixed an incorrect definition of the Fibonacci sequence. thank you for the request!

Recommended Posts

I want to write in Python! (1) Code format check
I want to write in Python! (2) Let's write a test
I want to write in Python! (3) Utilize the mock
I want to format and check Python code to my liking on VS Code
I want to be able to run Python in VS Code
I wrote the code to write the code of Brainf * ck in python
I want to do Dunnett's test in Python
I want to create a window in Python
I want to merge nested dicts in Python
I want to make C ++ code from Python code!
I want to write to a file with Python
I want to display the progress in Python!
I want to embed a variable in a Python string
I want to easily implement a timeout in python
Even in JavaScript, I want to see Python `range ()`!
I want to randomly sample a file in Python
I want to work with a robot in python.
Write tests in Python to profile and check coverage
I made an action to automatically format python code
I want to use the R dataset in python
I want to do something in Python when I finish
I want to manipulate strings in Kotlin like Python!
Automatically format Python code in Vim
Write selenium test code in python
I want to debug with Python
I want to do something like sort uniq in Python
I want to make input () a nice complement in python
I didn't want to write the AWS key in the program
I want to write a triple loop and conditional branch in one line in python
I tried to implement PLSA in Python
I tried to implement permutation in Python
I want to print in a comprehension
I want to solve APG4b with Python (only 4.01 and 4.04 in Chapter 4)
I tried to implement PLSA in Python 2
I want to use jar from python
I want to build a Python environment
I want to analyze logs with Python
LINEbot development, I want to check the operation in the local environment
I want to play with aws with python
How to check opencv version in python
[Python / AWS Lambda layers] I want to reuse only module in AWS Lambda Layers
I tried to implement ADALINE in Python
I wanted to solve ABC159 in Python
I tried to implement PPO in Python
format in python
I want to embed Matplotlib in PySimpleGUI
How to write Ruby to_s in Python
I wrote a code to convert quaternions to z-y-x Euler angles in Python
(Python Selenium) I want to check the settings of the download destination of WebDriver
I want to convert a table converted to PDF in Python back to CSV
I want to batch convert the result of "string" .split () in Python
I want to explain the abstract class (ABCmeta) of Python in detail.
Environment maintenance made with Docker (I want to post-process GrADS in Python
I want to color a part of an Excel string in Python
I made a script in python to convert .md files to Scrapbox format
I made a program to check the size of a file in Python
I want to do a monkey patch only partially safely in Python
I want to use MATLAB feval with python
I want to pin Datetime.now in Django tests
I want to memoize including Python keyword arguments
I was able to recurse in Python: lambda