Prompting for input until 2 blank lines are given - python

I need to prompt a user for input until 2 blank lines are given in a row, please note that the input read may have blank lines in it for clarity purposes, I will need two blank lines given back to back before it breaks.
So far I've come up with this:
def gather_intel():
done = False
while done is False:
data = raw_input("Copy and paste the work log: ")
if data is None:
done = True
How ever this will end as soon as a single blank line is given, I've also tried adding another while loop to it:
def gather_intel():
done = False
while done is False:
data = raw_input("Copy and paste the work log: ")
while data != "" + "\n" + "":
data = raw_input("Copy and paste the work log: ")
if data == "" + "\n" + "":
done = True
However this one is an infinite loop and will never end. How can I prompt a user for input, until there are two blank lines given to the input back to back?

number_of_empty_responses = 0
while True:
data = raw_input("Copy and paste the work log: ")
if data == "":
number_of_empty_responses += 1
if number_of_empty_responses == 2:
break
else:
number_of_empty_responses = 0
pass # Received data, perform work.

For future me or somebody else. The input until 2 conscutive newline characters:
def handy_input(prompt='> '):
'An `input` with 2 newline characters ending.'
all_input_strings = ''
# prompt the user for input
given_input = input(prompt)
all_input_strings += given_input
# and handle the two newline ending
while given_input:
# if previous input is not empty prompt again
given_input = input('')
all_input_strings += '\n' + given_input
return all_input_strings
And the answer to the question with 2 empty lines:
def empty_lines_input(prompt='> ', n_lines=2):
'An `input` with `n_lines` empty line ending.'
all_input_strings = ''
# prompt the user for input
given_input = input(prompt)
all_input_strings += given_input
# and handle the two newline ending
while n_lines>0:
# if previous input is not empty prompt again
given_input = input('')
all_input_strings += '\n' + given_input
# check if it was an empty line
if not given_input:
n_lines -= 1
else:
n_lines = 2
return all_input_strings

Related

Read the 3 next lines in python file

I want to read the 3 next lines in a file but from a given point
If a user is in the phonebook I display the user and the 3 next lines -> code snippet
import re
phonebook_rule = re.compile(r'\'\D{3,6}\'\'\D{3,13}\'\'\d{10}\'')
def myFunction(phonebooke):
print(phonebooke)
if begin == 1:
firstname = input('enter a firstname:')
lastname = input('enter a lastname:')
phone = input('enter a number:')
imp = (f'\'{firstname}\'\'{lastname}\'\'{phone}\'')
if phonebook_rule.match(imp):
phbook = open('Phonebook','a')
phbook.write('Fristname: ' + firstname + '\n')
phbook.write('Lastname: ' + lastname + '\n')
phbook.write('Phone: ' + phone + '\n')
phbook.close()
else:
print('Not a good format')
elif begin == 2:
search = input('Search a user:')
cnt = 1
if search in phbook.read():
print('This user is in the phonebook')
while True:
print(phbook.readlines())
cnt += 1
if cnt == 3:
break
else:
print('No user found')
else:
print('nothing')
begin = int(input('Chose a number 1 to 4:'))
print(myFunction(begin))
Don't know how to do this , especially the part when I need to start from "search" input and then display the 3 other lines...
Edit:
That's the only things I get with readlines()
There's a user called Matt in my phonebook or maybe I did something wrong ?
It might help to reinitialize the file object. I suspect that this is will do what you're looking for.
search = input('Search a user:')
phbook.close()
phbook = open('Phonebook','r')
for line in phbook:
line = line.strip()
if search in line:
print('This user is in the phonebook')
print(line) # print the line where you found the string
for _ in range(2):
print(phbook.readline()) # print the next 2 lines
break
else:
print('No user found')

how to write an encryption program in python

I am needing a bit of help on my encryption program. Instead of having the program just move the letters by two (c would become a or r would become p) I'd like to be able to have it reference 2 lists, the first one going from a-z normally and the other with letters in different order to act as the encrypt/decrypt side. Hopefully that makes sense. Here's what i have so far.
result = ''
choice = ''
message = ''
while choice != 0:
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if choice == '1':
message = input('\nEnter message for encryption: ')
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print(result + '\n\n')
result = ''
if choice == '2':
message = input('\nEnter message to decrypt: ')
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print(result + '\n\n')
result = ''
elif choice != '0':
print('You have entered an invalid input, please try again. \n\n')
This works fine and dandy but i'd like to have the lists. Lets say list 1 is A,B,C,D,E and list 2 would be W,N,U,D,P. just for ease of use purposes.
Here is a solution, for small letters only. It can easily be modified to handle also capital letters, by adding them to the text strings.
As can be seen, the space character is at the same position in both lists. This is not necessary, as any character can be translated to any other. However if the decrypted or encrypted is not containing unique characters only, the program will break down.
decrypted = b"abcdefghijklmnopqrstuvwxyz "
encrypted = b"qwertyuiopasdfghjklzxcvbnm "
encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)
result = ''
choice = ''
message = ''
while choice != '0':
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if choice == '1':
message = input('\nEnter message for encryption: ')
result = message.translate(encrypt_table)
print(result + '\n\n')
elif choice == '2':
message = input('\nEnter message to decrypt: ')
result = message.translate(decrypt_table)
print(result + '\n\n')
elif choice != '0':
print('You have entered an invalid input, please try again. \n\n')
Ok, so a few things here...
First I'll give you exactly what you were looking for and explain what I used and some of the changes that needed to be made to your original code. Then I'll explain some inherent issues what what you're trying to do and suggest some areas to read up on/some ways you might want to improve what you've got.
Here's the code you're looking for (while retaining the same flow as what you submitted put above):
import random
result = ''
choice = ''
message = ''
characters_in_order = [chr(x) for x in range(32,127)]
while choice != 0:
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if str(choice) == '1':
message = input('\nEnter message for encryption: ')
r_seed = input('Enter an integer to use as a seed: ')
random.seed(r_seed)
shuffled_list = [chr(x) for x in range(32,127)]
random.shuffle(shuffled_list)
for i in range(0, len(message)):
result += shuffled_list[characters_in_order.index(message[i])]
print(result + '\n\n')
result = ''
elif str(choice) == '2':
message = input('\nEnter message to decrypt: ')
r_seed = input('Enter an integer to use as a seed (should be the same one used to encrypt): ')
random.seed(r_seed)
shuffled_list = [chr(x) for x in range(32,127)]
random.shuffle(shuffled_list)
for i in range(0, len(message)):
result += characters_in_order[shuffled_list.index(message[i])]
print(result + '\n\n')
result = ''
elif str(choice) != '0':
print('You have entered an invalid input, please try again. \n\n')
You'll notice that I set a global 'characters in order' list, which is just every ASCII character (32-126) in order. I also imported the 'random' module and used this to shuffle the characters in order according to a seed that the user inputs. As long as this seed is the same on the encryption and decryption end, it will produce the same shuffled list and it should work to encrypt or decipher the same string. Also notice the str() around your input choices. Without that, the user had to input '1', rather than 1 to submit a choice without an error.
All of that said...
Notice that the way the new function works is by looking at a character's index in one list and pulling out the character at that index in another. The method you were using, of incrementing or decrementing a character's ASCII code is basic (though not much more basic than this), but it also has a pretty critical flaw, which is that characters on one end or another of the ASCII set wouldn't return ASCII characters. If you were encrypting it at a bit-level, which would be preferred, this wouldn't matter/would be irrelevant, but here you're not going to get the kind of string back that you want if you were to, for example, enter a [space] (ASCII 32) into your plaintext to be encrypted.
If you're interested, you might want to read up on symmetric key encryption/DES for some ideas on how encryption is really done, though props on the start/interest and this can certainly be a fun way to create some sort of cryptogram puzzle or something along those lines. I won't pretend to be any kind of expert, but I can at least point you in the write direction. (https://en.wikipedia.org/wiki/Data_Encryption_Standard https://en.wikipedia.org/wiki/Symmetric-key_algorithm)
Consider having your code read in a .txt file and print out to a .txt file, rather than using user input for the message.
Again, I'm not an expert by any means and there are definitely some fun uses of the kind of program you're aiming for, just trying to point you in the right direction if this is something that you're interested in. Hope all of that is helpful!
Here is my solution. It uses a randomizer to encrypt the file by assigning a ASCII value to the plain text and randomly shifts it around.
from random import randint
import sys
def menu():
input1=int(input(""" please select what you want to do:
1.Encrypt
2.Decrypt
3.Extended Encryption
4.exit
"""))#menu to choose what you want to do
if input1==1:
encrypt() #takes you to the encrypt function
elif input1==2:
decrypt()#takes you to the decrypt function
elif input1==3:
enxtended()#takes you to the extended encryption function
elif input1==4:
sys.exit #exits the program
else:
print("invalid entry try again")
menu()
def encrypt():
file_name=str(input("please enter the name of the file that you want to open\n"))
try:
text_file=open(file_name + ".txt","r")#puts the text file into read
text_file=text_file.read()#reads the text file
print(text_file)#prints the strings in the document
except:
print("error try again")
encrypt()
random(text_file)
def random(text_file):
list1=("")#creates blank string
for x in range (0,8):
num=(randint(33,126))#generates a random number between33 and 126
ascii1=chr(num) #converts it into an ascii character
list1=list1+ascii1#adds the ascii character to the blank string list1
print (f"your 8 key code is {list1}") #prints 8 character code
offset(list1,text_file)
def offset(list1,text_file):
total=0
for x in range (8,):
total=total+ord(list1[x]) #turns each character into an ascii value
total=total/8 #divides it by
total=round(total,0)#rounds it to 0 decimel places
print(total)
total=total-32#minuses 32 from total
print(f"your offset factor is {total}")
encrypting(total,text_file)
def encrypting(total,text_file):
length=len(text_file)
string1=("")
for x in range (length,):
numascii=ord(text_file[x])#turns the characters into its ascii value
numascii=int(numascii)#makes sure they are integers
if numascii==32:
letter=chr(32)#converts spaces back into spaces
string1=string1+letter#adds space to thestring
else:
numascii1=numascii+total#adds the character value to the offset factor
numascii1=int(numascii1)#makes sure it is an integer
if numascii1>126:# if the ascii value is great then 126
numascii1=numascii1-94#minus 94 from it
letter=chr(numascii1)#turn it into a character
string1=string1+letter#add it to the string
else:
letter=chr(numascii1)#turn the ascii value into a character
string1=string1+letter#add it to the string
print(f"your encrypted file is {string1}")
savefile(string1)
menu()
I have written separate programs for encryption and decryption. Both of these use file manipulation techniques. Use the username 'eggs' and password 'chicks' so that not anyone can see my secret code. I have used hashlib for more security. Just change the User 'Soumajit' to your respective Username to make it work. The first one is encryption and the next one is for decryption.
#ENCRYPTION
from time import sleep
import subprocess
import hashlib
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
def en():
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&* ()`-+=1234567890"
encrypt = ""
decrypt = ""
print
print "Type y for yes and anything else for no"
start = raw_input("Do you want to import file from desktop? ")
if start == "y":
Open = raw_input("Enter the .txt file you want to open in desktop: ")
a = open("C://Users//Soumajit//Desktop//" + Open + ".txt", "r")
print
x = (a.read())
copy2clip(x)
a.close()
print "Right click and select paste below to encrypt"
print
message = raw_input()
for i in message:
x = alphabet.find(i)
new = (x - 5) % 74
encrypt += alphabet[new]
e2 = encrypt[::-1]
else:
print "Type your message below"
message = raw_input("")
for i in message:
x = alphabet.find(i)
new = (x - 5) % 74
encrypt += alphabet[new]
e2 = encrypt[::-1]
print
a = raw_input("By what name do you want to save it?: ")
file = open(a + ".txt", 'wb')
file.write(e2)
file.close()
copy = raw_input("Do you want to copy your file? ")
if copy == 'y':
copy2clip(e2)
print 'Your encrypted file has been copied to the clipboard'
else:
print "Your encrypted file has been saved with the name " + str(a) + " in desktop"
print "To decrypt it, use my other program"
sleep(3)
u = 'e415bf03b4d860dccba57cea46371f831d772ba1deca47f28fa7d1f7'
p = 'c35f7f79dc34a678beb2b4106c84c9963561e7c64bc170e50c429b9a'
ur = raw_input('Enter your username: ')
ur1 = hashlib.sha224(ur).hexdigest()
pr = raw_input('Enter your password: ')
pr1 = hashlib.sha224(pr).hexdigest()
if ur1 == u and pr1 == p:
print 'Access granted'
sleep(1)
en()
else:
print "Incorrect username or password"
sleep(1)
#DECRYPTION
from time import sleep
import subprocess
import hashlib
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
def de():
print "Type y for yes and anything else for no"
start = raw_input("Do you want to import file from desktop? ")
if start == "y":
Open = raw_input("Enter the .txt file you want to open from folder: ")
a = open("C://Users//Soumajit//Desktop//" + Open + ".txt", "r")
x = (a.read())
#print x
copy2clip(x)
print "Right click and select paste below to decrypt"
print
message = raw_input()
a.close()
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&*()`-+=1234567890"
decrypt = ''
for i in message:
x = alphabet.find(i)
new = (x + 5) % 74
decrypt += alphabet[new]
d2 = decrypt[::-1]
d3 = d2.replace("`", " ")
final = d3.replace("2", " ")
print
print final
else:
print "Type or paste your encrypted text below"
print
message = raw_input()
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&*()`-+=1234567890"
decrypt = ''
for i in message:
x = alphabet.find(i)
new = (x + 5) % 74
decrypt += alphabet[new]
d2 = decrypt[::-1]
d3 = d2.replace("`", " ")
final = d3.replace("2", " ")
print
print final
u = 'e415bf03b4d860dccba57cea46371f831d772ba1deca47f28fa7d1f7'
p = 'c35f7f79dc34a678beb2b4106c84c9963561e7c64bc170e50c429b9a'
ur = raw_input('Enter your username: ')
ur1 = hashlib.sha224(ur).hexdigest()
pr = raw_input('Enter your password: ')
pr1 = hashlib.sha224(pr).hexdigest()
if ur1 == u and pr1 == p:
print 'Access granted'
sleep(1)
de()
print
end = raw_input('press q to quit: ')
while end != 'q':
print 'You did not type q'
end = raw_input('press q to quit: ')
if end == 'q':
quit()
else:
print 'Incorrect username or password'
sleep(1)
quit()

Trying to make encryption program which reads and writes to files and encrypts with two keywords. len() function not working

Trying to create an encryption/decryption program in python that reads a message from a file, encrypts with two keywords then outputs to another file. Also, it can do this in reverse.
I'mm having an issue with the len() function:
I get the error: object of type built in function or method has no len() in this section of code:
if (len(line)) == 0:
fileRead = True
In context this is the whole program:
print("Welcome to Python Encrypt 2015")
print("Only enter alphabet charcters into the file - no punctuation!")
#repeat loop for using program again and so on...
finished = False
while not finished:
#input and validation of encrypt/decrypt input
option = input("Do you want to encrypt or decrypt? (E/D): ")
while "E" != option != "D":
option = input("Only input 'E' or 'D'! Do you want to encrypt or decrypt? (E/D): ")
#file to be encrypted/decrypted is opened to read
message = ""
fileRead = False
if option == "E":
file = open("Task3Decrypted.txt","r")
else:
file = open("Task3Encrypted.txt","r")
#message from 'to encrypt' file is read and outputted to variable
while not fileRead:
line = (file.readline()).strip()
if line.isalpha()==True:
line = line.lower
else:
input("Message contains numbers or symbols. Please correct! Press any key to continue: ")
sys.exit
if (len(line)) == 0:
fileRead = True
else:
message = message + line
#file closed - saving it
file.close()
#validating keyword and stretching and cutting to length of message
key1True = False
while key1True == False:
keyword1 = input("Enter your first keyword: ")
if keyword1.isalpha()==True:
keyword1 = keyword1.lower()
key1True = True
key1length = len(keyword1)
while len(keyword1)<len(message):
keyword1=keyword1+keyword1
keyword1=keyword1[:len(message)]
key2True = False
while key2True == False:
keyword2 = input("Enter your second keyword: ")
if keyword2.isalpha()==True:
keyword2 = keyword2.lower()
key2True = True
key2length = len(keyword2)
while len(keyword2)<len(message):
keyword2=keyword2+keyword2
keyword2=keyword2[:len(message)]
newMessage = ""
for i in range(len(message)):
char = ord(message[i])-96
key1 = ord(keyword1[i])-96
key2 = ord(keyword2[i])-96
if char==-64:
newMessage = newMessage+" "
else:
if option == "E":
#clearing original file for security
clearFileE = open("Task3Decrypted.txt","w")
clearFileE.close
#encryption
if char+key1+key2>26:
newMessage = newMessage+chr(char+key1+key2-26+96)
else:
newMessage = newMessage+chr(char+key1+key2+96)
newFile = open("Task3Encrypted.txt","w")
newFile.write(newMessage)
newFile.close()
else:
clearFileD = open("Task3Encrypted.txt","w")
clearFileD.close
#decryption
if char-key1-key2<1:
newMessage = newMessage+chr(char-key1-key2+26+96)
else:
newMessage = newMessage+chr(char-key1-key2+96)
newFile = open("Task3Decrypted.txt","w")
newFile.write(newMessage)
newFile.close()
carryOn = input("Do you want to encrypt/decrypt another message? (Y/N): ")
while "Y" != carryOn != "N":
carryOn = input("Only input 'Y' or 'N'! Do you want to encrypt/decrypt another message? (Y/N): ")
if carryOn == "N":
finished = True
Thanks in advance!
You left off the parentheses in
line = line.lower()
Without the (), you're setting line to the object of the lower() function itself, hence the error message.

How can i make this program faster(more efficient)?

I have this code that creates unique passwords using the first letter of each word from the file.Before each password is created(written to a file) it is compared to all passwords that are currently in the file, so if the file has 50,000 passwords before a another is written it has to scan through all 50k.
A user can input any amount of passwords needed but the bigger the number the longer it takes 100k will take a long time how can i optimize this to make the program run faster ? The password generation is not included code
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
*new Code - i used the set function *
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")
else:
new_passwords = set(line.strip() for line in open ("MnemPass.txt"))
for num in range(passnum):
temp = generatePassword()
if temp not in new_passwords:
CurrentPasswords.add(temp)
else:
"match found"
for pw2 in CurrentPasswords:
storePass.write(pw2 + "\n")
You can considerably reduce runtime by loading the file once and then appending each new password to it rather than open file in loop and check line by line,Here I am using uuid in generatePassword() to generate a random string of length between 3 and 10
Your code:
def func(passnum):
import os,uuid,random
def generatePassword():
return str(uuid.uuid4()).replace('-', '')[0:random.randint(3,10)]
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
I slightly modified it to load the file at starting itself and append for every new password, notice that we don't need inner for loop anymore, the code becomes:
def func2(passnum):
import uuid
import os, random
linelength = 0
fileData = []
if os.path.isfile('MnemPass.txt'):
f = open("MnemPass.txt", "r")
fileData += f.read().splitlines()
linelength = len(fileData).__int__()
f.close()
def generatePassword():
return str(uuid.uuid4()).replace('-', '')[0:random.randint(3,10)]
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")
filemax = linelength
num = linelength # Number used to cycle through array set to size of list
# print(linelength+10)
if newpass in fileData:
print ("match found: PASSWORD : " , fileData.index(newpass))
passMatch = open("Matchpassword.txt", "a")
passMatch.write(newpass)
passMatch.write("\n")
passMatch.close()
else:
linelength += 1
fileData.append(newpass)
storePass = open("MnemPass.txt", "a")
storePass.write(newpass)
storePass.write("\n")
storePass.close()
print ("NEW WRITTEN")
if linelength == filemax:
num = num - 1
Profile for your code:
Profile for modified code:
As you can see the runtime has reduced from 45secs to 27secs ! :)
NOTE:
I ran the tests for 10000 passwords and deleted the generated files for next pass :)
In the case that your code runs in a loop as you present here:
Checking the whole file on every loop iteration is not very efficient.
It is much more efficient to keep a set of created passwords and check if a new password is already in the set before adding it.
Also in this case you should only open the file once outside the main for loop and close it afterwards.
In the case that your program adds only one password and then returns, it is better to add each new password in a way that your file remains sorted. This way you can use binary search to search if a password already exists.

Outputting loop data to a text document in python

I currently have the following code: You enter a string, the computer then pulls random letters and tries to match it to the letters in your string. This repeates and with each iteration the computer gets closer to guessing your string. I would like to output the initial string entered or the 'target' and the string format of the number of iterations it took to get the correct match. I want to output this to a text document. So far the script produces a text document but does not output to it. I would like it to save the data after each iteration from the main loop. I have the working program i just need assitance with the output, any ideas on how that could be done?
Here is the progress i made:
import string
import random
possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:£$^%&*|'
file = open('out.txt', 'w')
again = 'Y'
while again == 'Y' or again == 'y':
target = input("Enter your target text: ")
attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
attemptNext = ''
completed = False
generation = 0
while completed == False:
print(attemptThis)
attemptNext = ''
completed = True
for i in range(len(target)):
if attemptThis[i] != target[i]:
completed = False
attemptNext += random.choice(possibleCharacters)
else:
attemptNext += target[i]
generation += 1
attemptThis = attemptNext
genstr = str(generation)
print("Target matched! That took " + genstr + " generation(s)")
file.write(target)
file.write(genstr)
again = input("please enter Y to try again: ")
file.close()
Addressing both the original question and the one in the comments:
How to write to file after each iteration of the loop: call file.flush() after file.write(...) :
file.write(target)
file.write(genstr)
file.flush() # flushes the output buffer to the file
To add a newline after each "target" and "genstring" that you write, well, add a newline to the string (or whatever other output formatting you want) :)
file.write(target + '\n')
file.write(genstr + '\n')

Categories