如何有效地以上限宽度水平书写6行六边形?

时间:2019-06-21 20:47:43

标签: python python-3.x string optimization

我需要以有效的时间有效地以上限宽度存储/打印6个线符号,以构建表示形式并进行打印。当前,它们存储为对象列表,其中 str 属性是六行六边形。

我尝试嵌套循环,并观察到我的编码效率消失了。

from enum import Enum
import base64
import random

SOLID = '==========\n'
BROKEN = '====  ====\n'

# Snipped 2D array of hexagrams for lookup table called HEXAGRAMS

SORTED_HEXAGRAMS = sorted(sum(HEXAGRAMS, []), key=lambda h: h.value)

def build_hexagram_output(hexagrams):
    output = "\n"
    for hexagram in hexagrams:
        output += str(hexagram) + "\n"
    return output


def encode(msg, shuffle=False, file=False):
    if shuffle:
        print("Shuffling...")
        shuffled = ''.join(random.sample(B64_CHARACTERS, len(B64_CHARACTERS)))
        print("Key: {}".format(shuffled))
        KEYMAP.update(zip(shuffled, SORTED_HEXAGRAMS))
    else:
        KEYMAP.update(zip(B64_CHARACTERS, SORTED_HEXAGRAMS))
    if file:
        msg = "./" + msg
        with open(msg, 'rb') as f:
            b64_encoded = base64.b64encode(f.read()).decode('utf-8')
    else:
        b64_encoded = base64.b64encode(bytes(msg, encoding='utf-8')).decode('utf-8')
    hexagrams = []
    for letter in b64_encoded.replace('=', ''):
        hexagrams.append(KEYMAP[letter])
    return build_hexagram_output(hexagrams)


class Trigram(Enum):
    HEAVEN = 0
    LAKE = 1
    FIRE = 2
    THUNDER = 3
    WIND = 4
    WATER = 5
    MOUNTAIN = 6
    EARTH = 7

    def __str__(self):
        if self.value == 0:
            return SOLID + SOLID + SOLID
        elif self.value == 1:
            return BROKEN + SOLID + SOLID
        elif self.value == 2:
            return SOLID + BROKEN + SOLID
        elif self.value == 3:
            return BROKEN + BROKEN + SOLID
        elif self.value == 4:
            return SOLID + SOLID + BROKEN
        elif self.value == 5:
            return BROKEN + SOLID + BROKEN
        elif self.value == 6:
            return SOLID + BROKEN + BROKEN
        elif self.value == 7:
            return BROKEN + BROKEN + BROKEN

class Hexagram:
    def __init__(self, upper, lower, value):
        self.upper = upper
        self.lower = lower
        self.value = value

    def __str__(self):
        return str(self.upper) + str(self.lower)

我想要它的当前输出:

====  ====
==========
====  ====
====  ====
====  ====
====  ====

==========
==========
==========
====  ====
====  ====
==========

====  ====
==========
==========
==========
====  ====
==========

要水平出现:

====  ==== ========== ====  ====
========== ========== ==========
====  ==== ====  ==== ==========
====  ==== ====  ==== ==========
====  ==== ========== ====  ====
====  ==== ========== ==========

编辑:

感谢Prune提供正确的答案,并让我走上正确的道路。这些不是随机的,而是移位密码-因此,在对整个消息进行编码之前,我不必构建行/列。最终成为我的最终解决方案。不是最漂亮的-但这很好用,我放弃了空格以获取更模糊的输出。

def build_hexagram_output(hexagrams):
    output = ""
    lines = [str()] * 6
    for hexagram in hexagrams:
        split_hexagram = str(hexagram).split("\n")
        for i in range(6):
            lines[i] += split_hexagram[i]
    position = 0
    total_position = 0
    while total_position <= len(lines[0]) - 1:
        for line in lines:
            output += line[total_position: total_position + MAX_WIDTH] + "\n"
            if position == 5:
                position = 0
            else:
                position += 1
        total_position += MAX_WIDTH
    return output
02:27:10 [jonesy@yeetbook] iching > python main.py -e ThanksPrune
==============  ================================================================
====  ================================================  ==================  ====
==============  ============================  ========  ========  ========  ====
==============  ========  ========  ========  ========  ========  ==============
====  ========  ========  ========  ============================  ========  ====
====  ========  ======================================  ========  ========  ====
====  ========  ========  ========  ============================  ====
====  ========  ======================================  ========  ====
==============  ============================  ========  ==============
==============  ==================  ========  ========  ==============
====  ============================  ============================  ====
==============  ======================================  ==============

1 个答案:

答案 0 :(得分:1)

由于该项目仅发出随机六边形,因此简单的方法是生成六行,每行三个符号。生成相同的18个符号,但按照生成的顺序打印它们,每3个组后都有一个换行符。

import random

for row in range(6):
    line = ""
    for col in range(3):
        line += random.choice(["========== ", "====  ==== "])
    print(line)

输出:

========== ====  ==== ========== 
========== ========== ========== 
====  ==== ====  ==== ====  ==== 
========== ====  ==== ========== 
====  ==== ====  ==== ====  ==== 
========== ========== ====  ==== 

您已经做了很多无关的工作来维护程序不使用的表示形式。如果您需要评估产生的三元组,那么使用基础二进制代码就很容易了。保留每个所选符号的位,然后在事实之后的 中将其转换为三元组和六元组代码:

symbol = ["========== ", "====  ==== "]
gram = [""] * 6
for row in range(6):
    line = ""
    for col in range(3):
        bar = random.randint(0, 1)
        line += symbol[bar]
        gram[col] += str(bar)
    print(line)

print(col)

您现在将col作为三个二进制字符串,每个六进制表示一个。您可以根据需要简单地将其分解为三字母组合;将每个数字从二进制转换为十进制,您就有索引供分析使用。对于上面的示例,col显示为

"001010" "101110" "001011"