[GO] I wrote the code to write the code of Brainf * ck in python

Introduction

I wanted to write the code with Brainfuck, but it seemed to be a pain to write the code, so I decided to have python write it instead. However, I can't make something that difficult, so I made a program that outputs a character string as it is.

environment

Practice

Stupid way

The first thing I thought about was to convert each character of the string received as input to ASCII and then simply increment the pointer and output it. In terms of code, it looks like this.

makebf0.py



import os

#Already hoge.Delete any file called bf
if os.path.exists("/hoge.bf"):
    os.remove("hoge.bf")

s = input()
array = []

#Get ASCII for each character
for si in s:
    array.append(ord(si))

f = open("hoge.bf", "w")
for ai in array:
    for i in range(ai):
        f.write("+")
    f.write(".>")

#new line
f.write("++++++++++++.")
f.close()

When you do this

$ python makebf0.py
brainf*ck
$ cat hoge.bf

hoge.bf


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.>++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++.>++++++++++++.

Code like this is generated.

This makes the code long and uninteresting, so I'll try to compress the generated code.

Code improvements

The idea for compressing the code was to use a loop to reduce the number of +. As an algorithm, if the number of loop turns is n and the ASCII of the i-th character of the string is si, min (si / n, si / n + 1) is incremented in the loop and the fraction is the loop. Incremented or decremented outside. I tried to generate the code with the smallest number of +. The code looks like this.

makebf1.py


import os
import math

if os.path.exists("./hoge2.bf"):
    os.remove("hoge2.bf")

s = input()
array= [] #Character si ascii
for si in s:
    array.append(ord(si))

f = open("hoge2.bf", "w")

MAX = 0
for ai in array:
    if MAX < ai:
        MAX = ai

list = [] #Difference

#i's decisive decision
for i in range(MAX):
    if i == 0:
        continue
    sum = i 
    for ai in array:
      
        r1 = ai // i
        r2 = (ai + i) // i

        if ai - r1 * i > r2 * i - ai:
            r = r2 * i - ai
            sum += r2
        else :
            r = ai - r1 * i
            sum += r1

        sum = sum + r
        list.append(sum)

m = 10000000000
for i in range(len(list)):
    #print(li)
    li = list[i]
    if m > li:
        #print(li)
        m = li
        std = i

#Number of times to turn the loop
for i in range(m):
    f.write('+')

flag = []
#Loop contents
f.write('[')
for ai in array:
    r1 = ai // m 
    r2 = (ai + m) // m 
    f.write('>')

    if ai - r1 * m > r2 * m - ai:
        flag.append(-(r2 * m - ai))
        for j in range(r2):
            f.write('+')

    else:
        flag.append(ai - r1 * m)
        for j in range(r1):
            f.write('+')


#Return pointer to loop counter
for i in range(len(array)):
    f.write('<')
f.write('-')
f.write(']')

#Handle fractions
for i in range(len(array))
    f.write('>')
    if flag[i] < 0:
        for j in range(-flag[i]):
            f.write('-')
    else:
        for j in range(flag[i]):
            f.write('+')
    f.write('.')

#Begin on a new line
f.write('>++++++++++++.')
f.close()

When you run

$ python makebf1.py
brainf*ck
$ cat hoge2.bf

hoge2.bf


+++++++++++++++++++++[>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++++
<<<<<<<<<-]>-------.>+++++++++.>--------.>.>+++++.>---.>.>------.>++.>++++++++++++.

The code has been compressed considerably. I was able to generate code in 158 bytes in compressed code, compared to 921 bytes in straightforward code. You did it.

At the end

How was it

I wasn't used to writing python, so I was able to write this code to get used to python a bit. Brainfuck is also an interesting language so I would like to be able to do more complicated things. If you have any better algorithms or bad things about your code, please let us know. Thank you for reading this far.

Referenced articles

https://qiita.com/TomoShiozawa/items/25dcce1540085df71053 https://qiita.com/saba383810/items/39e20b11c71b3dfd2589

Recommended Posts

I wrote the code to write the code of Brainf * ck in python
I want to write in Python! (1) Code format check
I want to write in Python! (3) Utilize the mock
Part 1 I wrote the answer to the reference problem of how to write offline in real time in Python
I wrote the queue in Python
I wrote the stack in Python
Part 1 I wrote an example of the answer to the reference problem of how to write offline in real time in Python
First python ② Try to write code while examining the features of python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I wrote "Introduction to Effect Verification" in Python
The trick to write flatten concisely in python
I want to display the progress in Python!
I wrote a code to convert quaternions to z-y-x Euler angles in Python
I want to batch convert the result of "string" .split () in Python
I want to explain the abstract class (ABCmeta) of Python in detail.
I tried to get the authentication code of Qiita API with Python.
I made a program to check the size of a file in Python
I tried to graph the packages installed in Python
I wrote python in Japanese
How to get the number of digits in Python
[Fundamental Information Technology Engineer Examination] I wrote the algorithm of Euclidean algorithm in Python.
I want to use Python in the environment of pyenv + pipenv on Windows 10
I stumbled on the character code when converting CSV to JSON in Python
I felt that I ported the Python code to C ++ 98.
I tried to refactor the code of Python beginner (junior high school student)
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
I want to use the R dataset in python
I tried to summarize the string operations of Python
[Note] How to write QR code and description in the same image with python
I used Python to find out about the role choices of the 51 "Yachts" in the world.
The 15th offline real-time I tried to solve the problem of how to write with python
I tried to find the entropy of the image with python
I tried the accuracy of three Stirling's approximations in python
I wrote the basic grammar of Python with Jupyter Lab
I wrote the basic operation of Seaborn in Jupyter Lab
I tried to summarize the code often used in Pandas
[Python] I tried to visualize the follow relationship of Twitter
I wrote it in Go to understand the SOLID principle
I just wrote the original material for the python sample code
I tried to implement the mail sending function in Python
I wrote the basic operation of Numpy in Jupyter Lab.
I want to know the features of Python and pip
I want to be able to run Python in VS Code
I tried to implement blackjack of card game in Python
I didn't want to write the AWS key in the program
In the python command python points to python3.8
I wrote Fizz Buzz in Python
Write selenium test code in python
How to write offline real time I tried to solve the problem of F02 with Python
I tried to create a Python script to get the value of a cell in Microsoft Excel
How to determine the existence of a selenium element in Python
I compared the calculation time of the moving average written in Python
How to implement Java code in the background of RedHat (LinuxONE)
How to know the internal structure of an object in Python
[Python] I wrote the route of the typhoon on the map using folium
[Python] PCA scratch in the example of "Introduction to multivariate analysis"
[Cloudian # 9] Try to display the metadata of the object in Python (boto3)
How to check the memory size of a variable in Python
[Introduction to Python] I compared the naming conventions of C # and Python.
Output the contents of ~ .xlsx in the folder to HTML with Python
Feel free to change the label of the legend in Seaborn in python