我正在制作一个二进制随机化程序,该程序将文本随机化,然后输出随机二进制。但在将 7 位二进制对象返回到列表的部分无法正常工作。
import random
message = input('What is your message? ')
def encrypter(message):
shuffled = []
second = []
ascii,binary = [],[]
for letter in message:
ascii.append(ord(letter))
for letter in ascii:
binary.append(int(bin(letter)[2:]))
print(binary)
for character in binary:
for digit in str(character):
shuffled.append(digit)
print(shuffled)
random.shuffle(shuffled)
print(shuffled)
previous_number = 0
current_string = ''
for digit in shuffled:
if len(current_string) < 7:
current_string += digit
previous_number = previous_number + 1
elif len(current_string) == 7:
second.append(int(current_string))
previous_number = 0
current_string = ''
我尝试将 elif 语句更改为 else 语句,但仍然没有成功。 它似乎无法读取字符串的长度。我还尝试将其从检查字符串的长度更改为使用类似的计数器
number = previous_number+1
if number < 7:
etc
据我所知,您希望从输入的随机二进制表示中获得 7 位数字的分块输出。这将做到这一点。长度检查没有失败,但是您每次都使用
current_string = ''
重置输出,因此,即使您修复它以返回输出,您也只是继续丢弃之前的字符串。
基本上,我刚刚从规范中获取了分块代码,然后添加了一个列表理解来将分块列表中的数字连接起来。
import random
message = input('What is your message? ')
def encrypter(message, chunk_size=7):
shuffled = []
second = []
ascii,binary = [],[]
for letter in message:
ascii.append(ord(letter))
for letter in ascii:
binary.append(int(bin(letter)[2:]))
print(binary)
for character in binary:
for digit in str(character):
shuffled.append(digit)
print(shuffled)
random.shuffle(shuffled)
print(shuffled)
chunked = [
shuffled[i:i + chunk_size] for i in range(0, len(shuffled), chunk_size)
]
joined = [''.join(item) for item in chunked]
return joined
result = encrypter(message=message)
print(result)