-2

我正在尝试编写一个程序,该程序以随机​​顺序生成一个从 1 到 26 的数字列表,然后使用该列表“加密”给定的单词,以便将字母表的第 n 个字母映射到第 n 个随机列表中的数字。例子:

随机列表是:

[8,2,25,17,6,9,12,19,21,20,18,3,15,1,11,0,23,14,4,7,24,5,10,13,16,22]

这意味着单词act变成[8,25,7],单词xyzzy变成[13,16,22,22,16]

我有以下代码,但我不确定如何继续:

#8a
def randomalpha():
    a=[0]*26
    count = 0
    while count < 25:
        r = randrange(0,26)
        if r not in a:
            a[count] = r
            count += 1
    return(a)
print(f())
#8b
ls=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def encrypt(alphabet):
    a=randomalpha()
    count=0
    b=input('enter a word')
    for i in b:               #not sure if i am ok up to here but this is when i got really confused 


print(encrypt(ls))
4

3 回答 3

2

我的看法:

from string import ascii_lowercase
from random import shuffle

def char2num(chars):
    r = range(len(chars))
    shuffle(r)
    return dict(zip(chars, r))

def encrypt(s, lookup):
    return ' '.join(str(lookup[ch]) for ch in s)

print encrypt('cat', char2num(ascii_lowercase))
于 2013-04-14T00:38:52.557 回答
0
import random
import string

def randomalpha():
    nums, result = range(26), [] # [0, 1, 2, 3, ... --> 25]
    random.shuffle(nums)
    for i in range(26):
        result.append(nums.pop())
    return result

def encrypt(s):
    alphabet = list(string.lowercase) # ['a', 'b', 'c', ... --> 'z']
    key = dict(zip(alphabet, randomalpha()))
    return ''.join([str(key[ltr]) for ltr in s])

参考:

于 2013-04-14T00:25:35.373 回答
0

由于今天提出的这个问题而在此处添加此内容:将数字分配给字母表的最简单方法?

 import random, string
    alpha = list(string.ascii_lowercase)
    numLst = list()
    while len(numLst) != 26:
        num = random.randint(1,26)
        if (num not in numLst):
            numLst.append(num)

现在您所要做的就是索引列表以获取字母和相应的唯一随机数。例如 alpha[0] 为您提供“a”,而 numLst[0] 将为您提供相应的唯一编号。

于 2019-09-05T19:13:51.003 回答