codewars(python)练习笔记二十三:Brainfuck Translator(Brainfuck翻译)

题目

Introduction

Brainfuck is one of the most well-known esoteric programming languages. But it can be hard to understand any code longer that 5 characters. In this kata you have to solve that problem.

Description

In this kata you have to write a function which will do 3 tasks:

  1. Optimize the given Brainfuck code.
    
  2. Check it for mistakes.
    
  3. Translate the given Brainfuck programming code into C programming code.
    

More formally about each of the tasks:

  1. Your function has to remove from the source code all useless command sequences such as: '+-', '<>', '[]'. Also it must erase all characters except +-<>,.[].
    Example:
  "++--+." -> "+."
  "[][+++]" -> "[+++]"
  "<>><" -> ""
  1. If the source code contains unpaired braces, your function should return "Error!" string.

  2. Your function must generate a string of the C programming code as follows:

  • Sequences of the X commands + or - must be replaced by *p += X;\n or *p -= X;\n.

Example:

"++++++++++" -> "*p += 10;\n"
"------" -> "*p -= 6;\n"
  • Sequences of the Y commands > or < must be replaced by p += Y;\n or p -= Y;\n.
    Example:
">>>>>>>>>>" -> "p += 10;\n"
"<<<<<<" -> "p -= 6;\n"
  • . command must be replaced by putchar(*p);\n.
    Example:
".." -> "putchar(*p);\nputchar(*p);\n"
  • , command must be replaced by *p = getchar();\n.
    Example:
"," -> "*p = getchar();\n"
  • [ command must be replaced by if (p) do {\n. ] command must be replaced by } while (p);\n.
    Example:
"[>>]" ->
if (*p) do {\n
  p += 2;\n
} while (*p);\n
  • Each command in the code block must be shifted 2 spaces to the right accordingly to the previous code block.
    Example:
"[>>[<<]]" ->
if (*p) do {\n
  p += 2;\n
  if (*p) do {\n
    p -= 2;\n
  } while (*p);\n
} while (*p);\n

Examples

Input:
+++++[>++++.<-]
Output:
*p += 5;
if (*p) do {
  p += 1;
  *p += 4;
  putchar(*p);
  p -= 1;
  *p -= 1;
} while (*p);

Sample Tests

def testing(code, expected):
    result = brainfuck_to_c(code)
    test.assert_equals(result, expected)
    
test.describe("general tests")
test.it("basic")

testing("++++", "*p += 4;\n")
testing("----", "*p -= 4;\n")

testing(">>>>", "p += 4;\n");
testing("<<<<", "p -= 4;\n");
    
testing(".", "putchar(*p);\n");
testing(",", "*p = getchar();\n");
    
testing("[[[]]", "Error!");
    
testing("[][]", "");
    
testing("[.]", "if (*p) do {\n  putchar(*p);\n} while (*p);\n");

testing("[]][", "Error!");

testing("++ ++", "*p += 4;\n");

testing("> <<", "p -= 1;\n");

testing("[[.]]", "if (*p) do {\n  if (*p) do {\n    putchar(*p);\n  } while (*p);\n} while (*p);\n");

我的解法

最初版:

#!/usr/bin/python


def brainfuck_sum(l):
    r = ''
    if l['key'] == '+':
        r = '*p += ' + str(l['value']) + ';\n'
    if l['key'] == '-':
        r = '*p -= ' + str(l['value']) + ';\n'
    if l['key'] == '<':
        r = 'p -= ' + str(l['value']) + ';\n'
    if l['key'] == '>':
        r = 'p += ' + str(l['value']) + ';\n'
    return r


def brainfuck_add(i):
    r = ''
    if i == ',':
        r = "*p = getchar();\n"
    if i == '.':
        r = "putchar(*p);\n"
    if i == '[':
        r = "if (*p) do {\n"
    if i == ']':
        r = "} while (*p);\n"
    return r


def brainfuck_retract(i, p):
    r = ''
    p_count_l = p[0:i].count('[')
    p_count_r = p[0:i+1].count(']')
    p_count = p_count_l - p_count_r
    for t in range(p_count):
        r += '  '
    return r


def brainfuck_to_c(source_code):
    p = source_code
    for i in p:
        if i not in ['+', '-', '<', '>', '.', ',', '[', ']']:
            p = p.replace(i, '')
    while '+-' in p or '-+' in p or '<>' in p or '><' in p or '[]' in p:
        p = p.replace('+-', '').replace('-+', '').replace('<>', '').replace('><', '').replace('[]', '')
    if '[' in p or ']' in p:
        if p.count('[') != p.count(']') or p.index('[') > p.index(']'):
            return 'Error!'
    r = ''
    l = {'key': 'p', 'value': 0}
    for i in range(len(p)):
        r += brainfuck_retract(i, p)
        r += brainfuck_add(p[i])
        if p[i] == '<' or '>' or '+' or '-':
            if p[i] == l['key']:
                l['value'] += 1
            else:
                r += brainfuck_sum(l)
                l['key'] = p[i]
                l['value'] = 1
        else:
            r += brainfuck_sum(l)
            l['key'] = ''
            l['value'] = 0
    if l['value'] != 0:
        r += brainfuck_sum(l)
    return r

部分优化版本:

解法一代码太过于冗长,做边界测试的时候直接内存过载,所以要优化代码。
简单看了一下,决定要把while 循环的部分拿掉,优化思路,看看代码执行情况。

#!/usr/bin/python


def brainfuck_sum(l):
    r = ''
    if l['key'] == '+-':
        if l['value'] > 0:
            r = '*p += ' + str(l['value']) + ';\n'
        elif l['value'] < 0:
            r = '*p -= ' + str(-l['value']) + ';\n'
    if l['key'] == '<>':
        if l['value'] < 0:
            r = 'p -= ' + str(-l['value']) + ';\n'
        elif l['value'] > 0:
            r = 'p += ' + str(l['value']) + ';\n'
    return r


def brainfuck_add(i):
    r = ''
    if i == ',':
        r = "*p = getchar();\n"
    if i == '.':
        r = "putchar(*p);\n"
    if i == '[':
        r = "if (*p) do {\n"
    if i == ']':
        r = "} while (*p);\n"
    return r


def brainfuck_retract(i, p):
    r = ''
    p_count_l = p[0:i].count('[')
    p_count_r = p[0:i+1].count(']')
    p_count = p_count_l - p_count_r
    for t in range(p_count):
        r += '  '
    return r


def brainfuck_to_c(source_code):
    p = source_code
    print(p)
    for i in p:
        if i not in ['+', '-', '<', '>', '.', ',', '[', ']']:
            p = p.replace(i, '')
    if '[]' in p:
        p = p.replace('[]', '')
    if '[' in p or ']' in p:
        if p.count('[') != p.count(']') or p.index('[') > p.index(']'):
            return 'Error!'
    r = ''
    l = {'key': '', 'value': 0}
    for i in range(len(p)):
        if p[i] in '+-':
            if l['key'] != '+-':
                r += brainfuck_sum(l)
                l['key'] = '+-'
                l['value'] = 0
            l['value'] += (1 if (p[i] == '+') else -1)
        elif p[i] in '<>':
            if l['key'] != '<>':
                r += brainfuck_sum(l)
                l['key'] = '<>'
                l['value'] = 0
            l['value'] += (-1 if (p[i] == '<') else 1)
        elif p[i] in ['.', ',', '[', ']']:
            r += brainfuck_retract(i, p)
            r += brainfuck_add(p[i])
    if l['value'] != 0:
        r += brainfuck_sum(l)
    print(r)
    return r

目前最终版:

解法二解决了内存过载的问题,但在边界测试的时候,仍然会遇到Max Buffer Size Reached (1.5 MiB),这个说明代码尽管优化了一部分,但还需要继续优化。但仔细思考了一下,还是把while循环的部分添加上,只是作为单列的代码(这一部分是我觉得题目是有争议的,我没想清楚,思考部分在最后)。最终形成了以下解法:

#!/usr/bin/python


def brainfuck_sum(l):
    res = ''
    if l['key'] == '+-':
        if l['value'] > 0:
            res = '*p += ' + str(l['value']) + ';\n'
        elif l['value'] < 0:
            res = '*p -= ' + str(-l['value']) + ';\n'
    elif l['key'] == '<>':
        if l['value'] < 0:
            res = 'p -= ' + str(-l['value']) + ';\n'
        elif l['value'] > 0:
            res = 'p += ' + str(l['value']) + ';\n'
    else:
        pass
    return res


def brainfuck_add(i):
    r = ''
    if i == ',':
        r = "*p = getchar();\n"
    elif i == '.':
        r = "putchar(*p);\n"
    elif i == '[':
        r = "if (*p) do {\n"
    elif i == ']':
        r = "} while (*p);\n"
    else:
        pass
    return r


def brainfuck_retract(i, p):
    r = ''
    p_count_l = p[0:i].count('[')
    p_count_r = p[0:i+1].count(']')
    p_count = p_count_l - p_count_r
    for t in range(p_count):
        r += '  '
    return r


def brainfuck_replace(p):
    while '+-' in p or '-+' in p or '<>' in p or '><' in p or '[]' in p:
        p = p.replace('+-', '').replace('-+', '').replace('<>', '').replace('><', '').replace('[]', '')
    return p


def brainfuck_to_c(source_code):
    p = source_code
    print(p)
    for i in p:
        if i not in ['+', '-', '<', '>', '.', ',', '[', ']']:
            p = p.replace(i, '')
    p = brainfuck_replace(p)
    if '[' in p or ']' in p:
        if p.count('[') != p.count(']') or p.index('[') > p.index(']'):
            return 'Error!'
    if p == '':
        return ''
    r = ''
    l = {'key': '', 'value': 0}
    for i in range(len(p)):
        if p[i] in '+-':
            if l['key'] != '+-':
                r += brainfuck_sum(l)
                l['key'] = '+-'
                l['value'] = 0
            l['value'] += (1 if (p[i] == '+') else -1)
        elif p[i] in '<>':
            if l['key'] != '<>':
                r += brainfuck_sum(l)
                l['key'] = '<>'
                l['value'] = 0
            l['value'] += (-1 if (p[i] == '<') else 1)
        elif p[i] in ['.', ',', '[', ']']:
            r += brainfuck_retract(i, p)
            r += brainfuck_add(p[i])
    if l['value'] != 0:
        r += brainfuck_sum(l)
    return r

思考:

我最终把while循环部分添加上了,主要是这里面我觉得题目是有争议的。
例如题目要求:"Your function has to remove from the source code all useless command sequences such as: '+-', '<>', '[]'. Also it must erase all characters except +-<>,.[]."
Is this rule recursive?
For example:

"<[+-]>" -> "<[]>"
"<[+-]>" -> ""

Which one is right?
(I guess the second is right, just want to be sure.)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,096评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 8,541评论 0 23
  • 这个夏天终于走到了最后,送君千里,终须一别。当我像往常一样跟那些女孩们打招呼的时候,她们依旧是笑靥如花,而...
    黎梨Lee阅读 492评论 0 3
  • 七七和苏山离婚了。 “我太累了,每天凌晨就要起来买菜做饭打扫房间,到了七点半准时去上班,下班顺路接孩子回家,做饭洗...
    挖坑君阅读 454评论 1 12
  • 这次天气预报的高温预警很准, 太阳一出来, 汗水流成了小溪。 气温高烧到40度, 田里的庄稼已快要休克。 玉米叶子...
    将山走成平路阅读 265评论 2 5