Algorithm learned with Python 3rd: Radix conversion

#Algorithm learned in Python

Introduction

Implement the basic algorithm in Python to deepen your understanding of the algorithm. The third step is radix conversion. By the way, I will also touch on bit operations.

Radix conversion

Converting a radix (the number of numbers to be handled) by changing a decimal number to a binary number and vice versa. We will implement them and review the radix conversion.

Radix conversion ver.1

First, implement a program that converts a decimal number to a binary number very easily based on the principle. The code is shown below.

code

radix_conversion1.py


"""
2020/12/16
@Yuya Shimizu

Radix conversion ver.1
Decimal number → binary number
"""
a = 18
result = ' '

#Decimal number → binary number
while a > 0:
    result = str(a%2) + result
    a //= 2

print(result)
output
10010 

Conversion to a decimal number is completed by dividing the number represented by the decimal number by 2, repeating until the quotient becomes 0, and then arranging the remainder from the back. In the above program, repetition is expressed by while a> 0:` ``, and characters are combined with str (a% 2) in front so that they can be arranged from the back. It is carried out. Since conversion to other base numbers can be performed in the same way, in ver.2, we put them together in a function and converted them to other base numbers. However, since it is only a simple structure, it can only represent up to decimal numbers.

Radix conversion ver.2

Implement a program that converts a decimal number into another decimal number in a function. The code is shown below.

code

radix_conversion2.py


"""
2020/12/16
@Yuya Shimizu

Radix conversion ver.2
Decimal number → n-ary number
"""

#Simple function
def convert(n, base):
    result = ' '

    #Decimal number → n-ary number
    while n > 0:
        result = str(n%base) + result
        n //= base

    print(result)


n = 18
convert(n, 2)
convert(n, 4)
convert(n, 8)

#Functions related to the prepared decimal numbers and binary numbers
print(bin(n))

output
10010 
102 
22 
0b10010

The program in the function is almost the same as ver.1. However, conversion to binary numbers can be done more easily with the functions already prepared. `bin ()`. If you look at the top and bottom of the output, you can see that it is certainly converted to a binary number. 0b will be described later. Next, ver.3 shows a program that converts a binary number back to a decimal number.

Radix conversion ver.3

Implement a program that converts a binary number back to a decimal number. The code is shown below.

code

radix_conversion3.py


"""
2020/12/16
@Yuya Shimizu

Radix conversion ver.3
Binary number → decimal number
"""

#Simple function
def Re_convert(n):
    result = 0
    #Binary number → decimal number
    for i in range(len(n)):
        result += int(n[i]) * (2**(len(n) - i - 1))

    print(result)


n = '10010'
Re_convert(n)

#Functions provided(Argument is a character type)
print(int(n, 2))    

#Another way
a = 0b10010 #By adding 0b, it is treated as an integer type ← The result is the same as above
print(a)

output
18
18
18

It can be seen that all the same results are obtained. As before, you can use the provided function `int ()`. The first argument is a character type number, and the second argument is a binary number. Then, it is converted to a decimal number as an int (integer) type. There is another method, and by adding 0b, it will be treated as an integer type. I specified it as a character type earlier, but if you express a binary number after 0b, it will indicate a decimal number when you do `` `print``` without interposing the previous processing.

Bit operation

It is an operation that is often used in logic circuits, but processing for these can also be performed using similar functions, so let's take a look. Here, we deal with AND, OR, exclusive OR, left shift, and right shift. The code is shown below.

code

bit_Operation.py


"""
2020/12/16
@Yuya Shimizu

Bit operation
"""
a = 0b10010
b = 0b11001

#Bit inversion
print(bin(~a), bin(~b))

#Logical AND(AND)
print(bin(a & b))

#Logical sum(OR)
print(bin(a | b))

#Exclusive OR(XOR)
print(bin(a ^ b))

#Left shift
print(bin(a << 1))

#Shift right
print(bin(b >> 2))

output
-0b10011 -0b11010
0b10000
0b11011
0b1011
0b100100
0b110

It can be seen that the output is calculated correctly except for 0b.

Impressions

I had never done bitwise operations in python, so it was good to know how to handle bitwise operations. In addition, I was able to know that int, which was used only for integer conversion, can be used for radix conversion, and that there is another function called bin. I've known the mechanism of radix conversion itself, but I think it was a good opportunity to reconfirm it here.

References

Introduction to algorithms starting with Python: Standards and computational complexity learned with traditional algorithms Written by Toshikatsu Masui, Shoeisha

Recommended Posts

Algorithm learned with Python 3rd: Radix conversion
Algorithm learned with Python 10th: Binary search
Algorithm learned with Python 5th: Fibonacci sequence
Algorithm learned with Python 9th: Linear search
Algorithm learned with Python 4th: Prime numbers
Algorithm learned with Python 2nd: Vending machine
Algorithm learned with Python 19th: Sorting (heapsort)
Algorithm learned with Python 12th: Maze search
Algorithm learned with Python 11th: Tree structure
Algorithm learned with Python 16th: Sorting (insertion sort)
Algorithm learned with Python 14th: Tic-tac-toe (ox problem)
Algorithm learned with Python 15th: Sorting (selection sort)
Algorithm learned with Python 17th: Sorting (bubble sort)
Algorithm learned with Python 18th: Sorting (stack and queue)
[Python3] Dijkstra's algorithm with 14 lines
[Python] Object-oriented programming learned with Pokemon
MP3 to WAV conversion with Python
Perceptron learning experiment learned with Python
Python data structures learned with chemoinformatics
Efficient net pick-up learned with Python
1. Statistics learned with Python 1-1. Basic statistics (Pandas)
Implementation of Dijkstra's algorithm with python
Python algorithm
[Python] Reactive Extensions learned with RxPY (3.0.1) [Rx]
Search the maze with the python A * algorithm
1. Statistics learned with Python 1-3. Calculation of various statistics (statistics)
Let's develop an investment algorithm with Python 1
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Latitude / longitude coordinates ↔ UTM coordinate conversion with python
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
1. Statistics learned with Python 1-2. Calculation of various statistics (Numpy)
python starts with ()
Bingo with python
The 3rd Algorithm Practical Test (PAST) Explanation (Python)
Zundokokiyoshi with python
Use Python and word2vec (learned) with Azure Databricks
1. Statistics learned with Python 2-1. Probability distribution [discrete variable]
Find the shortest path with the Python Dijkstra's algorithm
Solving the Python knapsack problem with the greedy algorithm
Excel with Python
Microcomputer with Python
"Principle of dependency reversal" learned slowly with Python
Cast with python
I learned Python with a beautiful girl at Paiza # 02
I learned Python with a beautiful girl at Paiza # 01
The first algorithm to learn with Python: FizzBuzz problem
Problems when creating a csv-json conversion tool with python
1st Algorithm Practical Test Solve past questions with python
I tried "morphology conversion" of images with Python + OpenCV
Perform half-width / full-width conversion at high speed with Python
Serial communication with Python
Django 1.11 started with Python3.6
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python