我有這個代碼,它使用文件中每個單詞的第一個字母創建唯一的密碼。在每個密碼創建(寫入文件)之前,它將與當前在文件中的所有密碼進行比較,因此如果文件具有在寫入另一個密碼之前需要50,000個密碼,它必須掃描所有50k。 用戶可以輸入任意數量的密碼,但數字越大需要花費的時間越長,需要很長時間我如何優化這個以使程序運行更快?口令產生不包括代碼如何讓這個程序更快(更高效)?
for mainLoop in range(passnum):
user = 0
newpass = generatePassword() # New password generated each iteration of loop
storePass = open("MnemPass.txt","a")
print ("PASSWORD GENERATED ")
#Checks if file is empty if True write first password
fileEmpty = os.stat("MnemPass.txt").st_size == 0
if fileEmpty == True:
storePass.write(newpass)
storePass.write("\n")
storePass.close()
print ("FIRST PASSWORD WRITTEN")
#IF file is not empty Read line by line and compare each with new password generated returns boolean value
elif fileEmpty == False:
storePass = open("MnemPass.txt","r")
with open("MnemPass.txt") as f:
fileData = f.read().splitlines()
linelength = len(fileData).__int__()
filemax = linelength
num = linelength #Number used to cycle through array set to size of list
#print(linelength+10)
for iterate in range(linelength):
num = num - 1 #Number decreases each pass
#print num
if fileData[num] != newpass: # The last element in the array is checked first decrementing each pass
go = True
if fileData[num]==newpass: #changed
print ("match found: PASSWORD : "+fileData[num])
passMatch = open("Matchpassword.txt","a")
passMatch.write(newpass)
passMatch.write("\n")
passMatch.close()
go = False
break
#places new password once it does not match and all elements prev passwords are compared
if go == True and num == 0:
storePass = open("MnemPass.txt","a")
storePass.write(newpass)
storePass.write("\n")
storePass.close()
print ("NEW WRITTEN")
if linelength == filemax:
num = num -1
*新的代碼 - 我使用的設定功能*
passnum = (input("How many passwords do you need :")) sTime = datetime.now()storePass = open ("MnemPass.txt","a") # file open out of loop to increase speed fileEmpty = os.stat("MnemPass.txt").st_size == 0
new_passwords = set() CurrentPasswords = set()
if fileEmpty == True: while len(new_passwords)!= passnum: #will cause problems if dictionary cannot create amount needed new_passwords.add(generatePassword())
for pw in new_passwords: storePass.write(pw + "\n")
其他:開放(「MnemPass.txt線路 new_passwords =集(line.strip() 「)) 有效範圍內的NUM(passnum): 溫度= generatePassword()
if temp not in new_passwords: CurrentPasswords.add(temp) else: "match found"
爲PW2在CurrentPasswords: storePass.write(對W2 +「\ n」)
如果這是**工作代碼**,你認爲可以改進,它可能更適合[codereview.se]。 – jonrsharpe
高雅其工作確定生病做 –
運行時間可能取決於你的'generatePassword()'方法是如何有效的太 –