I just wanted to mess with my friend a little and wanted to text him in Brainfuck. Being a coder like me, I decided, why not just write a quick script to translate it for me?

Considering that most characters that I will be using in a regular English chat will be between 0-127, the algorithm will take the nearest factor of ten. Then it will add the result of the char number modulus that factor. Then I will translate that into Brainfuck.

I am ready to take all criticism so please give your opinion. Also, please test in and find any case where my algorithm will fail.

def letter_to_brainfuck(letter):
    num = ord(letter)
    return '+'*int(num / 10) + '[>++++++++++<-]>' + '+'*(num % 10)

def brainfuck_print(letter_list):
    return ''.join([i +'.>\n' for i in letter_list])

print(brainfuck_print([letter_to_brainfuck(i) for i in list(input())]))

1 Answer 1


If you pass a long text to the code generator, the resulting program will overflow its memory. This is because you do >+++.> for each character, but you never come back to clean up behind you. Instead of >+++.>, the generated code should be >+++.[-]<, which is slower but can handle arbitrary long text.

You say that your text contains mostly ASCII characters. Therefore it is probably more efficient to add or subtract the difference of the characters. In pseudo code:

curr = 0
for ch in str:
    if ch > curr:
        emit_add(ch - curr)
    if ch < curr:
        emit_sub(curr - ch)
    curr = ch

Emitting only the difference is especially efficient for long runs of lowercase ASCII letters.

Regarding your Python code: are you sure that Python really does not have a repeat string function? The letter_to_brainfuck function would become a one-liner then.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.