waker0086 / HW-NKcode

https://www.nowcoder.com/exam/oj?page=1&pageSize=50&search=&tab=%E5%90%8D%E4%BC%81%E7%9C%9F%E9%A2%98&topicId=37
0 stars 0 forks source link

HJ36-字符串加密 #中等#字符串 #27

Open waker0086 opened 2 years ago

waker0086 commented 2 years ago

https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3

waker0086 commented 2 years ago

思路

我的

题中说保证输入是小写,所以没考虑大小写

def hj36():
    key,encode =input(),input()
    #原始密钥去重
    L1=[]
    for i in key:
        if i not in L1:
            L1.append(i)
    L2=L1  #新密钥

    L3=[]  #正常字母表
    #填充小写字母表
    for j in range(97,123):
        L3.append(chr(j))
        if chr(j) not in L2:
            L2.append(chr(j))
    #输出加密结果
    res=''
    for i in encode:
        res += L2[L3.index(i)]  #!!注意此处不是L2()

    print(res)
    return

hj36()

考虑输入大小写

def hj36():
    key,encode =input(),input()
    #处理密钥
    L1=[]
    for i in key.upper():
        if i not in L1:
            L1.append(i)
    L2=L1
    #正常字母表
    L3=[]
    #填充大写字母表
    for j in range(65,91):
        L3.append(chr(j))
        if chr(j) not in L2:
            L2.append(chr(j))
    #输出加密结果
    res=''
    for i in encode:
        if i.isupper():
            res += L2[L3.index(i)]
        else :
            res += L2[L3.index(i.upper())].lower()

    print(res)
    return

hj36()

其他

  1. 首先生成正常字母顺序表
    
    l = [] 
    for i in range(26): 
     l.append(chr(ord('a')+i))

while True: try: key, s = input(), input()

2. 其次生成密匙

new = [] for i in key: if i not in new: new.append(i) for i in l: if i not in new: new.append(i)


3. 此时已经建立建立了新的密匙,如何与正常字母顺序表进行对照,
这里可以用一个python3中的**zip方法**,生成字典表

`m = dict(zip(l,new))`

> zip(l,new) 返回一个l和new一一对应的元组
>  dict(~) 把元组变成dict,l是key,new是value

4.  生成最终结果

res = [] for i in s: res.append(m[i]) print(''.join(res))

except: break

waker0086 commented 2 years ago

Python3 zip() 函数

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

我们可以使用 list() 转换来输出列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

https://www.runoob.com/python3/python3-func-zip.html

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped)  # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c))              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]

>>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>