python笔记 shuffle和permutation

函数shuffle与permutation都可以打乱数组元素顺序,区别在shuffle直接在原来的数组上进行操作,而permutation不直接在原来的数组上进行操作,会返回一个新的打乱顺序的数组。

import numpy as np

a = np.arange(4)
print('a:', a)
b = np.random.shuffle(a)
print('a:',a)
print('b:',b)

print('='*20)

a = np.arange(4)
print('a:',a)
b = np.random.permutation(a)
print('a:',a)
print('b:',b)

'''
a: [0 1 2 3]
a: [0 1 3 2]
b: None  #shuffle没有返回值,直接在原数组上操作
====================
a: [0 1 2 3]
a: [0 1 2 3]
b: [2 1 0 3]
'''
Permutation Cipher(置换密码)是一种基于置换的加密算法,它将明文中的字符按照一定的规则进行重新排列,从而得到密文。下面是一个简单的Python实现: ```python import random def permutation_cipher_encrypt(plain_text, key): # 将明文转换成列表 plain_list = list(plain_text) # 计算需要填充的空格数 pad_len = len(key) - len(plain_list) % len(key) if pad_len < len(key): plain_list.extend([' '] * pad_len) # 将列表按照密钥分组 groups = [plain_list[i:i+len(key)] for i in range(0, len(plain_list), len(key))] # 对每个分组进行置换操作 cipher_list = [] for group in groups: cipher_group = [group[key.index(i)] for i in key] cipher_list.extend(cipher_group) # 返回密文 return ''.join(cipher_list) def permutation_cipher_decrypt(cipher_text, key): # 将密文转换成列表 cipher_list = list(cipher_text) # 将列表按照密钥分组 groups = [cipher_list[i:i+len(key)] for i in range(0, len(cipher_list), len(key))] # 对每个分组进行反置换操作 plain_list = [] for group in groups: plain_group = [group[i] for i in [key.index(j) for j in key]] plain_list.extend(plain_group) # 返回明文 return ''.join(plain_list).rstrip() # 测试 plain_text = 'This is a test message.' key = 'PERMUTATION' cipher_text = permutation_cipher_encrypt(plain_text, key) print(cipher_text) print(permutation_cipher_decrypt(cipher_text, key)) ``` 这个实现中,我们需要提供一个密钥(即置换表),用于指定字符的排列顺序。加密解密过程都是类似的,只是在置换操作的时候使用了不同的密钥。在加密过程中,我们需要将明文按照密钥分组,并对每个分组进行置换操作。在解密过程中,我们需要将密文按照密钥分组,并对每个分组进行反置换操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值