我正在尝试编写一个程序,以随机顺序生成一个数字从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))
答案 0 :(得分: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))
答案 1 :(得分: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])
参考文献:
答案 2 :(得分:0)
由于今天提出的这个问题而在此处添加:Easiest way to assign a number to the alphabet?
select fileextension,count( distinct filename) from table
group by fileextension
现在您要做的就是索引列表,以获取字母和相应的唯一随机数。例如alpha [0]给您“ a”,而numLst [0]给您相应的唯一编号。