首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用python加密数据

用python加密数据
EN

Code Review用户
提问于 2018-01-05 10:33:10
回答 1查看 3.6K关注 0票数 9

我只是想解决其中一个谜题,解释如下:

删除空格后的句子if man was meant to stay on the ground god would have given us roots是54个字符,因此它是以7行8列的网格形式编写的。编码的消息是通过在列中显示字符、插入空格、然后显示下一列和插入空格等方式获得的。例如,上面矩形的编码消息是: imtgdvs mayoogo anouuio ntnnlvt wttddes aohghn sseoau。

有关更多条件,请参考这里:

代码语言:javascript
复制
from math import ceil, sqrt
from string import whitespace

def encrypt(string):
    enc_string = string.translate(None,whitespace)
    length = len(enc_string)

    #calculate the no of colums for the grid
    columns = int(ceil(sqrt(length)))

    #form a list of strings each of length equal to columns
    split_string = [enc_string[i:i+columns] for i in range(0, len(enc_string), columns)]

    #encrypted list of strings
    new_string = []
    for string in split_string:

        for i in range(len(string)):
            try:
                #replace the element in the list with the new string
                new_string[i] = new_string[i].replace(new_string[i], new_string[i] + string[i])
            except IndexError:
                #exception indicates that the string needs be added with new Index
                new_string.append(string[i])

    return " ".join(new_string)

if __name__ == "__main__":
    s = raw_input().strip()
    result = encrypt(s)
    print(result)

如果可以避免多个for循环和任何其他改进,请帮助我。

EN

回答 1

Code Review用户

回答已采纳

发布于 2018-01-05 11:13:10

这似乎是一种很长的方法,可以将字符串连在一起,每一组甚至一组字符。实际上,您正在尝试使用给定字符串中的字符来构建方阵。Python有一个非常好的切片和步长特性,它可以在一个内联操作中执行相同的任务。

我冒昧重写了您的encrypt函数:

代码语言:javascript
复制
from math import ceil
from string import whitespace

def square_encrypt(str_input): # avoiding the name `string` as python has a module `string`
    str_input = str_input.translate(None, whitespace) # making a copy and overwriting input parameter
    square_size = int(ceil(len(str_input)**0.5)) # or int(ceil(sqrt(len(str_input))))
    encrypted_list = [str_input[i::square_size] for i in xrange(square_size)]
    return " ".join(encrypted_list)
票数 13
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/184347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档