我只是想解决其中一个谜题,解释如下:
删除空格后的句子
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。
有关更多条件,请参考这里:
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循环和任何其他改进,请帮助我。
发布于 2018-01-05 11:13:10
这似乎是一种很长的方法,可以将字符串连在一起,每一组甚至一组字符。实际上,您正在尝试使用给定字符串中的字符来构建方阵。Python有一个非常好的切片和步长特性,它可以在一个内联操作中执行相同的任务。
我冒昧重写了您的encrypt函数:
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)https://codereview.stackexchange.com/questions/184347
复制相似问题