编程珠玑之第三章习题3-3

一万年没有更新博客了

前言

最近在看《编程珠玑》,分享一些课后习题的代码。本章分享的是3-3。这题在书本的课后目录中并未写明相关参考代码,现有网络上的代码又比较复杂,于是分享一下我个人的思路

题目

编写一个“banner”函数,该函数的输入为大写字母,输出为一个字符数组,该数组以图形化的方式表示该字母。

思路

整体分为三个模块
pre_code --> encode --> decode

pre_code是预编码,将26个字母预先进行编码

encode模块,接受输入,将输入的字母转换为具体编码

decode模块,接受编码,然后解码为二维数组,进行输出,得到图像

我们举例说明:
现在对字母I进行编码,I的图像为
在这里插入图片描述
它可以编码成

8 4
0 2 0 4 x
2 6 0 1 b
2 6 1 3 x
6 8 0 4 x

第一行:输出的二维数组8行4列
第二行:从0~2行,0~4列,填充x
第三行:从2~6行,0~1列,填充b(block,后续转换为’ ')
第四行:从2~6行,1~3列,填充x
第五行:从6~8行,0~4列,填充x

通过这样的编码方式,将字母的图像信息转换为字符串,指导图像输出。解码的时候将对应位置填充的数据提取出来,处理二维数组即可得到图像

这种方式最麻烦的点就是预编码,只能手动编码

代码

from typing import List

code_map = dict()

def pre_encode():
    code_map['I'] = '''8 4
0 2 0 4 x
2 6 0 1 b
2 6 1 3 x
6 8 0 4 x
'''

def encode(s: str):
    return code_map[s]

def print_list(output: List[List]):
    for row in output:
        print(row)

def decode(code: str):
    lines = code.splitlines()
    list = lines[0].split(' ')
    output = [[' ' for _ in range(int(list[1]))] for _ in range(int(list[0]))]
    for i in range(1, len(lines)):
        row_upper, row_down, col_upper, col_down, word = lines[i].split(" ")
        for r in range(int(row_upper), int(row_down)):
            for c in range(int(col_upper), int(col_down)):
                if word == 'b':
                    word = ' '
                output[r][c] = word
    print_list(output)

def draw_word(s: str):
    code = encode(s)
    decode(code)

pre_encode()
draw_word('I')

输出

程序绘制字母I的图像,得到如下结果
在这里插入图片描述

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值