Comparison of R and Python writing (Euclidean algorithm)

Introduction

"R or Python, which one to do?" There are many articles like this in the world. You'll see a controversy that doesn't end on the day you search for "R Python." In general, "R is often used in data analysis specialization and academia." A phrase such as "Python is versatile and often used on the business side" is said.

However, when I read these articles When you actually code, you don't know what's different. After all it seems that you need to try both to know the difference ... With that in mind, I decided to write a simple program in both languages.

By the way, I have been in R for 1 year, and I usually play with data.frame in Tidyverse, so I rarely write control syntax like this one. Python has just finished building the environment, so this article is also for practice. If you have any mistakes or comments that there is a better code, please do not hesitate to contact us.

Euclidean algorithm

I will explain the Euclidean algorithm to be implemented this time. (I miss high school mathematics)

Euclidean algorithm is an algorithm for finding the ** greatest common divisor ** of two natural numbers. For that, we use the following properties

$ A and b are natural numbers $ $ Equation: For a = bq + r, gcd (a, b) = gcd (b, r) holds for $

Taking advantage of this property "Dividing $ a $ by $ b $ to calculate the remainder $ r_1 $" → "Dividing $ b $ by $ r_1 $ to calculate the remainder $ r_2 $" →… → "Divided by dividing $ r_ {n-1} $ by $ r_n " →gcd(r_{n-1}, r_n) = gcd(r_{n-2}, n_{n-1})= ...=gcd(b, r_1) = gcd(a, b) = r_n$ Find the greatest common divisor in the form of.

Implement function in R

#Euclidean algorithm
gcd <- function(a, b){
  if (!(a %% 1 == 0 & b %% 1 == 0 & a > 0 & b > 0)) {
    cat('Input is not a natural number, so start over')
    } else if (a < b) {
      w <- a
      a <- b
      b <- w
      
      while (b != 0) {
        r <- a %% b
        a <- b
        b <- r
        }
      return(a)      
      } else {
        while (b != 0) {
          r <- a %% b
          a <- b
          b <- r
          }
        return(a)
      }
  }
> gcd(50856, 96007)
[1] 163

Implemented in Python

#Euclidean algorithm
def gcd(a, b):
  if not (a % 1 == 0 and b % 1 == 0 and a > 0 and b > 0):
    print('Input is not a natural number, so start over')
  elif a < b:
    w = a
    a = b
    b = w
    
    while not b == 0:
      r = a % b
      a = b
      b = r
    else:
      return(a)
  else:
    while not b == 0:
      r = a % b
      a = b
      b = r
    else:
      return(a)
>>> gcd(50856, 96007)
163

Comparison of both languages

Let's take a look at the coding characteristics of both. (Note that this is a subjective judgment based on the attributes of the author!)

1. A quick look

It's almost the first time I've written Python, I was worried, "This isn't closed, but it works properly ...?" But it works perfectly. Is it the point where the convenience of this area is supported?

R is enclosed in parentheses, and Python is indented to indicate the beginning and end of the process. Using indentation may be better in terms of "processing + easier for the user to see". (I heard a rumor that the corresponding parentheses are colored with the new function of Rstudio, so I'm expecting it)

2. Control syntax

motion R Python
Function definition name <- function(argument){processing} def name(argument):processing
Conditional branch 1 if(Conditional expression){processing} if Conditional expression:processing
Conditional branch 2 else if(Conditional expression){processing} elif Conditional expression:processing
repetition while(Conditional expression){processing} while Conditional expression:processing

This is about the same. Forcibly speaking, the difference between else if and el if.

3. Operators, etc.

motion R Python
Integer quotient %/% //
Surplus %% %
Logical AND & and
Logical sum | or
denial ! not

In R, operators are consistently given symbols, while In Python, the alphabet is used for the part related to conditional branching.

While it is imagined that R logical operators are often used in filter processing, Is Python supposed to be used exclusively for conditional branching? (ʻIf not ~ is naturally easy to read, but filter (a == 1 and b <= 3 and ~) `seems to be long and difficult to read)

in conclusion

The above is a rough comparison, but I think that the advantages and disadvantages of both languages have become apparent. Personally, I was surprised at how easy it is to write Python control syntax.

This time, I compared the basis of the language called control syntax (= the part where the idea is strongly expressed). If I can afford it, I would like to compare data frame processing and so on.

Postscript

Review of control flow

I felt that there was a lot of waste in the code, so I rewrote it while referring to various things.

R

gcd <- function(a, b){
  if (!(a %% 1 == 0 & b %% 1 == 0 & a > 0 & b > 0)) {
    cat('Input is not a natural number, so start over')
  } else {
    if(a < b){
      tmp <- a; a <- b; b <- tmp
    }
    while(b != 0){
      r <- a %% b; a <- b; b <- r 
    }
    return(a)
  }
}

Python

def gcd(a, b):
  if not (a % 1 == 0 and b % 1 == 0 and a > 0 and b > 0):
    print('Input is not a natural number, so start over')
  else:
    if a < b:
      a, b = b, a
    while b != 0:
      a, b = b, a % b
    else:
      return b

Implementation using recursive functions

I was told about the recursive function in the comments, so I implemented it. As a caveat, if you repeat until b == 0, the argument violates the condition of a natural number, so you need to rewrite it so that it repeats until one time before (ʻa% b == 0`). is there.

def gcd(a,b):
  if not (a % 1 == 0 and b % 1 == 0 and a > 0 and b > 0):
    print('Input is not a natural number, so start over')
  else:
    if a < b:
      a, b = b, a
    if not a % b == 0:
      return gcd(b, a % b)
    else:
      return b

There is also a function called Recall for calling recursive functions

gcd <- function(a, b){
  if (!(a %% 1 == 0 & b %% 1 == 0 & a > 0 & b > 0)) {
    cat('Input is not a natural number, so start over')
  } else {
      if(a < b){
        tmp <- a; a <- b; b <- tmp
      }
      if(a %% b != 0){
        return(Recall(b, a %% b) #Or gcd(b, a %% b)
      } else{
        return(b)
      }
  }
}


Recommended Posts

Comparison of R and Python writing (Euclidean algorithm)
Non-recursive implementation of extended Euclidean algorithm (Python)
Euclidean algorithm and extended Euclidean algorithm
Example of reading and writing CSV with Python
Comparison of Python and Ruby (Environment / Grammar / Literal)
A quick comparison of Python and node.js test libraries
Comparison table of frequently used processes of Python and Clojure
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
Comparison of 4 Python web frameworks
Python 3 sorted and comparison functions
Comparison of Apex and Lamvery
Source installation and installation of Python
Works with Python and R
Comparison of how to use higher-order functions in Python 2 and 3
Comparison of data frame handling in Python (pandas), R, Pig
VBA users tried using Python / R: logical operations and comparison operations
Environment construction of python and opencv
The story of Python and the story of NaN
Java and Python basic grammar comparison
Explanation and implementation of ESIM algorithm
Installation of SciPy and matplotlib (Python)
Sorting algorithm and implementation in Python
This and that of python properties
Python CSV file reading and writing
Hashing data in R and Python
Reading and writing NetCDF with Python
Reading and writing CSV with Python
Implementation of Dijkstra's algorithm with python
Speed comparison of Python XML parsing
Reading and writing text in Python
Coexistence of Python2 and 3 with CircleCI (1.0)
Summary of Python indexes and slices
Reputation of Python books and reference books
Recommended books and sources of data analysis programming (Python or R)
Speed comparison of Wiktionary full text processing with F # and Python
Automatic acquisition of gene expression level data by python and R
Summary of differences between Python and PHP (comparison table of main items)
[Python] Basic pattern and usage of if statement (comparison operator and Boolean operator)
Installation of Visual studio code and installation of python
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
(Java, JavaScript, Python) Comparison of string processing
Comparison of Japanese conversion module in Python3
Extraction of tweet.js (json.loads and eval) (Python)
Algorithm learned with Python 8th: Evaluation of algorithm
Comparison of gem, bundler and pip, venv
Python algorithm
Connect a lot of Python or and and
python string comparison / use'list'and'in' instead of'==' and'or'
Reading and writing JSON files with Python
Comparison of class inheritance and constructor description
Explanation and implementation of Decomposable Attention algorithm
Comparison of Python serverless frameworks-Zappa vs Chalice
Comparison of L1 regularization and Leaky Relu
Easy introduction of python3 series and OpenCV3
[Python] Various combinations of strings and values
Idempotent automation of Python and PyPI setup
Full understanding of Python threading and multiprocessing
Comparison of matrix transpose speeds with Python
Project Euler # 1 "Multiples of 3 and 5" in Python
Speed comparison of murmurhash3, md5 and sha1
[Fundamental Information Technology Engineer Examination] I wrote the algorithm of Euclidean algorithm in Python.