python实现任意字符串矩阵加解密

算法描述

不管输入字符串多长,把该字符串填到一个刚好合适的N*N的正方形的格子中,然后以对角线为对称线,对格子里的字母进行交换,然后对折进行交换,列如,输入abcd则填入2x2的方格中:

a b
c d


先对角线交换,变为:

a c
b d

然后对折交换,变为:

b d
a c

则密文为:bdac
 

python实现

# 密文解密
import math

def Deco(mw):
    l = len(mw)
    n = int(math.sqrt(l))
    if n*n < l:
        n = n + 1
    a = [None] * n * n
    b = [None] * n * n
    for i in range(0,n*n):
        if i < l:
            a[i] = mw[i:i+1]
        else:
            a[i] = '-'
    #print(a)
    for i in range(0,n):   # 行
        for j in range(0,n):   # 列
            s = a[i*n+j]
            # 上下对折
            ti = n - i - 1
            tj = j

            # 斜对角线
            ii = tj
            jj = ti

            b[ii*n+jj] = s
    #print(b)
    ss = ""
    for i in range(0,n*n):
        if b[i] != '-':
            ss += b[i]
    return ss

# 密文
str = input("请输入密文:")
re = Deco(str)
print("明文:" + re)

 

你可能感兴趣的:(知识有价)