2017-07-24 51 views
1

前言:這是一項家庭作業,我不是在尋找完整的答案,只是在正確的方向上微調。我正在編寫一個簡單的加密程序,它將文件的名稱作爲輸入,打開它並用隨機轉移的行重寫它。我已經這樣做了,但我需要以某種方式記錄轉移的行號。我知道我需要寫一個新列表,並在索引+1後添加索引,但我不知道該把它放在哪裏。交換列表中的值並記錄原始索引

from random import * 
seed(123) 

text_file = input("Enter a name of a text file to mix: ") 
f = open(text_file, 'r') 
encrypted = open('encrypted.txt', 'w') 
index = open('index.txt', 'w') 
lines = [] 
for line in f: 
    line = line.strip('\n') 
    lines.append(line) 
ll=len(lines) 
new_dict = {} 
for line in lines: 
    new_dict[lines.index(line)+1] = line 
for i in range (0,ll*3): 
    random_one = randint(0,ll-1) 
    random_two = randint(0,ll-1) 
    temp1 = lines[random_one] 
    temp2 = lines[random_two] 
    lines[random_one] = temp2 
    lines[random_two] = temp1 
for line in lines: 
    encrypted.write(line + "\n") 
encrypted.close() 

正如你看到的,我也提出,將包含.txt文件作爲1的內容的字典:lineone 2:linetwo。但我不確定是否會更容易使用它,或者只是使用列表來跟蹤它。

編輯:我改變了我的代碼包括:

new_dict[random_one] = temp2 
new_dict[random_two] = temp1 

new_dict現在打印移位列表的順序正確,但在錯誤的索引。例如,1:line7 2:line11,但我希望索引匹配行號,這樣我就可以將密鑰打印到索引文件中用於解密。例如:7:line7 11:line11任何提示?

+0

你可能有興趣在使用洗牌算法來減少你目前做簿記量。你會發現[Fisher-Yates算法的Knuth實現](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm)很可能適合你的需求。 –

+0

如果'''new_dict'''包含你需要重建文件的信息,並且你已經正確實現了它(它有效),那麼在這一點上它是最簡單的,因爲它完成了。 – wwii

+1

你可能會發現[enumerate](https://docs.python.org/3/library/functions.html#enumerate)對於構造''''new_dict'''很有用:'''對於我,enumerate(行):...''' – wwii

回答

0

只要隨意洗牌一個numpy數組並隨機播放它們。因此,您可以稍後保存索引。

import numpy as np 

indices = np.arange(5) 
np.random.shuffle(indices) 
print(indices) 

版本不numpy的:

from random import shuffle 
indices = list(range(5)) 
shuffle(indices) 
+2

你可以用一個普通的列表來做到這一點。爲什麼要把Numpy帶入這個?此外,這是一項家庭作業,OP可能不允許使用Numpy。 –

+1

numpy和熊貓已經成爲它看起來選擇的矯枉過正的解決方案。爲什麼這裏需要numpy? – idjaw

+0

我添加了列表解決方案。感謝你們。 – BrutalGames

1

你實際上並不需要保存洗牌行的順序。您可以通過使用最初使用的相同隨機種子簡單地在需要時重新創建它。下面的代碼應該給你一些想法。

import random 

random.seed(123) 

# Create a simple list of strings 
a = list('abcdefgh') 
print(a) 

# Generate a shuffled list of indices 
indices = list(range(len(a))) 
random.shuffle(indices) 

# Shuffle a into b 
b = [] 
for i in indices: 
    b.append(a[i]) 
print(b) 

# Unshuffle b into c 
c = [None] * len(b) 
for i, v in zip(indices, b): 
    c[i] = v 
print(c) 

輸出

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] 
['b', 'e', 'f', 'g', 'd', 'h', 'c', 'a'] 
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']