How to store last three scores - python

I have been doing a school project recently which which is about a school maths quiz. I successfully done two of the three tasks of my project. However the third task is seeming quite difficult.
I'm currently trying to store the last three scores of that student. However I can't quite get it to work. I did have a look at this thread: Displaying only the highest of a person's 3 most recent scores, saved in a .txt file. However I am having an error in my code for the for:
scores = file.readlines()
Which gives me an error saying that it's not readable. So unfortunately I couldn't get that code to work.
So what I'm trying to do is score the last three scores of the student. Then if there is more then 3, then I want to delete the least recent score.
This is my code:
import random
import csv
import operator
import os.path
import sys
user_scores = {}
validclass = "No"
classfile = "Class"
studentteacher = "None"
while studentteacher == "None":
studentteacherinput = input("Are you a Teacher or a Student?")
if studentteacherinput == "Teacher":
studentteacher = "Teacher"
print(studentteacher)
elif studentteacherinput == "Student":
studentteacher = "Student"
print(studentteacher)
else:
print("Please enter the one applicable ' Student ' or ' Teacher '.")
while validclass == "No":
pupilclass = input("What class are you in or what class would you like to see??")
print(pupilclass)
if pupilclass == "1":
if os.path.exists("class1scores.txt") and studentteacher == "Teacher":
file = open("class1scores.txt", "r")
validclass = "Yes"
elif os.path.exists("class1scores.txt") and studentteacher == "Student":
file = open("class1scores.txt", "a")
classfile = "class1scores.txt"
validclass = "Yes"
else:
file = open("class1scores.txt", "w")
validclass = "Yes"
elif pupilclass == "2":
if os.path.exists("class2scores.txt") and studentteacher == "Teacher":
file = open("class2scores.txt", "r")
validclass = "Yes"
elif os.path.exists("class2scores.txt") and studentteacher == "Student":
file = open("class2scores.txt", "a")
classfile = "class2scores.txt"
validclass = "Yes"
else:
file = open("class1scores.txt", "w")
validclass = "Yes"
elif pupilclass == "3":
if os.path.exists("class3scores.txt") and studentteacher == "Teacher":
file = open("class3scores.txt", "r")
validclass = "Yes"
elif os.path.exists("class3scores.txt") and studentteacher == "Student":
file = open("class3scores.txt", "a")
classfile = "class3scores.txt"
validclass = "Yes"
else:
file = open("class1scores.txt", "w")
validclass = "Yes"
file.seek(0)
scores = file.readline()
if studentteacher == "Teacher":
teacherinput = input("How would you like to sort the list? ' Alphabetically ' to sort it alphabetically with the students highest score, ' Highest ' for the highest scores with highest to lowest or ' Average ' for average scores with highest to lowest")
if teacherinput == "Alphabetically":
print("alphabetically")
csv1 = csv.reader(file, delimiter = ",")
sort = sorted(csv1, key = operator.itemgetter(0))
for eachline in sort:
print(eachline)
sys.exit()
if teacherinput == "Highest":
print("Highest")
if teacherinput == "Average":
print("Average")
namecheck = "invalid"
while namecheck == "invalid":
name = input("Please enter your name?")
if name.isalpha():
print("Your name is valid.")
namecheck = "valid"
#file.write(name + ",")
else:
print("Please enter a valid name, only containing letters.")
operation = input("Hello %s! Would you like to do Addition, Subtraction or Multiplication" % (name))
score = 0
if operation == "Addition":
for i in range(0, 10):
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
answer = number1 + number2
question = input("What is " + str(number1) + " + " + str(number2))
if question.isdigit() == True:
int(question)
else:
question = input("Please enter a answer with digits only. What is " + str(number1) + " + " + str(number2))
if int(question) == answer:
score += 1
print("Correct!")
else:
print("Wrong!")
elif operation == "Subtraction":
for i in range(0, 10):
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
answer = number1 - number2
if number2 >= number1:
answer = number2 - number1
question = input("What is " + str(number2) + " - " + str(number1))
else:
question = input("What is " + str(number1) + " - " + str(number2))
if question.isdigit() == True:
int(question)
else:
if number2 >= number1:
answer = number2 - number1
question = input("Please enter a positive answer with digits only. What is " + str(number2) + " - " + str(number1))
else:
question = input("Please enter a positive answer with digits only. What is " + str(number1) + " - " + str(number2))
if int(question) == answer:
score += 1
print("Correct!")
else:
print("Wrong!")
elif operation == "Multiplication":
for i in range(0, 10):
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
answer = number1 * number2
question = input("What is " + str(number1) + " x " + str(number2))
if question.isdigit() == True:
int(question)
else:
question = input("Please enter a answer with digits only. What is " + str(number1) + " + " + str(number2))
if int(question) == answer:
score += 1
print("Correct!")
else:
print("Wrong!")
print("Your final score is %s/10, Well Done!" % (score))
#file.write(str(score) + "\n")
#This is the code which I was trying to use to get the last 3 scores.
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
if name not in user_scores:
user_scores[name] = [] # Initialize score list
user_scores[name].append(score) # Add the most recent score
if len(user_scores[name]) > 3:
user_scores[name].pop(0) # If we've stored more than 3, get rid of the oldest
file.close()
Sorry for the inefficient method, but it's just the way I like to think. And thanks for your time.
#This is the code which I was trying to use to get the last 3 scores.
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
if name not in user_scores:
user_scores[name] = [] # Initialize score list
user_scores[name].append(score) # Add the most recent score
if len(user_scores[name]) > 3:
user_scores[name].pop(0) # If we've stored more than 3, get rid of the oldest
So I took that from the link mentioned above. My aim is to try and only get three scores, and not above 3.

As you seem to know, there are different modes you can open()(2/3) a file in. If you use "a" or "w", you can't read from the file. You can add a "+", to allow reading, too, though:
open("file.txt","a+")
Also, I'm not sure what version of Python you're using, but file() is a built-in type and function in Python 2, so you shouldn't use it as a variable name if that's the version you're using.

Implement a queue - https://docs.python.org/2/library/collections.html#collections.deque
from collections import deque
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
if name not in user_scores:
user_scores[name] = deque(maxlen=3)
temp_q = user_scores[name]
temp_q.append(str(score))
user_scores[name] = temp_q
Now user scores is a dict with key as name, and values as a deque object with just 3 scores. You need to iterate through them, cast the queue to list and join the elements to write them to file.
filehandle = open('outputfile.csv' ,'w')
for key, values in user_scores.iteritems():
filehandle.write(name + ',')
filehandle.write(','.join(list(values)) + '\n')
filehandle.close()

Related

how to add an ordered score table with names

import random
number_correct = 0
def scorer():
global number_correct
if attempt == answer:
print("Correct.")
number_correct = number_correct + 1
else:
print('Incorrect. The correct answer is ' + str(answer))
name = input("Enter your name: ")
for i in range(10):
num1 = random.randrange(1, 100)
num2 = random.randrange(1, 100)
operation = random.choice(["*", "-", "+", "%", "//"])
print("What is the answer?", num1, operation, num2)
attempt = int(input(" "))
if operation == "+":
answer = num1 + num2
scorer()
elif operation == "-":
answer = num1 - num2
scorer()
elif operation == "*":
answer = num1 * num2
scorer()
elif operation == "%":
answer = num1 % num2
scorer()
elif operation == "//":
answer = num1 // num2
scorer()
print(name + ", you got " + str(number_correct) + " out of 10.")
I have made the quiz above and now want it to make a high-score table with the names and scores next to each other from highest to smallest.
I am trying to sort the scores first and this is what I have come up with:
scores = []
names = []
file = open("scores.txt","a")
addedline = number_correct
file.write('%d' % addedline)
file.close()
file = open("scores.txt","r")
for eachline in file:
scores.append(eachline)
x = scores.sort()
print(x)
file.close()
I don't think this works and am not sure how i will combine the names and scores at the end (making sure that the correct score is next to the correct name). Please help.
thanks
I'm not sure how exactly your textfile looks but I would suggest using a dictionary (as long as you do not have the same score more than once). Like this you could make the key your score and the value could be the name and the dictionary would automatically sort itself in order of the keys.
I would recommend storing the names and scores as a csv, then you could read the names with the scores and then sort with the score as a key.
with open("scores.txt", "a") as file:
file.write("%s, %s\n" % (name, number_correct))
with open("scores.txt", "r") as file:
data = [line.split(", ") for line in file.read().split("\n")]
data = sorted(data, key = lambda x: -int(x[1]))
print("\n".join(["%s\t%s" % (i[0], i[1]) for i in data]))

Python: Saving numbers error when saved as string

I'm having an issue with my code, here:
correct = 0
grade_book = {}
File = open('Test.txt', 'r')
for line in File:
name, scores = line.split(':')
grade_book[name] = scores.strip()
File.close()
print(grade_book)
name = input("Name: ")
if name in grade_book.keys():
grade_book[name] += ',' + correct
else:
grade_book[name] = correct
File = open('Test.txt', 'w')
for name, scores in grade_book.items():
out_line = str(name) + ':' + str(scores) + "\n"
File.write(out_line)
File.close()
The problem is that it gives an error stating:
TypeError: Can't convert 'int' object to str implicitly
This happens in the program when it tries to save 'correct' to an existing name in the file. I've tried to fix the problem with the following:
name = input("Name: ")
if name in grade_book.keys():
grade_book[name] += ',' + str(correct)
else:
grade_book[name] = correct
But the problem with this is that the number printed to file is always 0, despite 'correct' being assigned to numbers more than 0, such as 8. On the other hand it doesent give an error like before, just the problem above.
Any solutions to this?
Yeah, Im probably missing something really obvious here.
Code for 'correct':
def mainLoop():
global count
global correct
Num1 = randint(1, 10)
Num2 = randint(1,10)
Operand= randint(1,3)
if Operand == 1:
question = str(Num1) + " + " + str(Num2) + " = "
answer = Num1 + Num2
elif Operand == 2:
question = str(Num1) + " - " + str(Num2) +" = "
answer = Num1 - Num2
else:
question = str(Num1) + " x " + str(Num2) + " = "
answer = Num1 * Num2
userAnswer = int(input(question))
if userAnswer == answer:
correct += 1
Guess I'll post the whole code for reference:
from random import randint
import time
count = 0
correct = 0
def mainLoop():
global count
global correct
Num1 = randint(1, 10)
Num2 = randint(1,10)
Operand= randint(1,3)
if Operand == 1:
question = str(Num1) + " + " + str(Num2) + " = "
answer = Num1 + Num2
elif Operand == 2:
question = str(Num1) + " - " + str(Num2) +" = "
answer = Num1 - Num2
else:
question = str(Num1) + " x " + str(Num2) + " = "
answer = Num1 * Num2
userAnswer = int(input(question))
if userAnswer == answer:
correct += 1
grade_book = {}
File = open('Test.txt', 'r')
for line in File:
name, scores = line.split(':')
grade_book[name] = scores.strip()
File.close()
print(grade_book)
name = input("Name: ")
if name in grade_book.keys():
grade_book[name] += ',' + str(correct)
else:
grade_book[name] = str(correct)
File = open('Test.txt', 'w')
for name, scores in grade_book.items():
out_line = str(name) + ':' + str(scores) + "\n"
File.write(out_line)
File.close()
while count < 10:
mainLoop()
count += 1
Did the indends fast, may be wrong
Text File Exmple:
Test:1,5
John:1,0
You are running mainLoop after writing the scores to your file, so the file will not contain the correct scores. Just move the code that asks the questions 10 times (while count < 10 etc.) to above the code that writes the scores to the grade_book (if name in grade_book.keys(): etc.).
You may find it helpful to avoid using global variables. Instead, you could have a question function that returns True or False depending on whether the user responds correctly or not, and then we just use sum to count up the right and wrong responses.
from random import randint
import time
def question():
a = randint(1, 10)
b = randint(1,10)
operand= randint(1,3)
if operand == 1:
sign = '+'
answer = a + b
elif operand == 2:
sign = '-'
answer = a - b
else:
sign = 'x'
answer = a * b
user_answer = int(input('{} {} {} = '.format(a, sign, b)))
return user_answer == answer # returns True if correct, False if not
grade_book = {}
with open('Test.txt', 'r') as file:
for line in file:
name, scores = line.split(':')
grade_book[name] = scores.strip()
print(grade_book)
name = input("Name: ")
# Ask a question 10 times and sum up the correct responses
# (This works because sum counts True as 1 and False as 0)
correct = sum(question() for _ in range(10))
if name in grade_book.keys():
grade_book[name] += ',' + str(correct)
else:
grade_book[name] = str(correct)
with open('Test.txt', 'w') as file:
for name, scores in grade_book.items():
file.write('{}:{}\n'.format(name, scores))
In grade_book[name] = correct You assign integer value correct. So it should be:
name = input("Name: ")
if name in grade_book.keys():
grade_book[name] += ',' + str(correct)
else:
grade_book[name] = str(correct)
And You are not doing anything with "correct". It is always 0.

Python - how to sort a csv file using a list

I have placed data in a separate file from a quiz the user has done (by the way in the quiz the user selects one class out of three). Now I would like to sort that data which is in the file by alphbetical, the highest score and the average score for each class.
if MyClass == "1":
myFile = open('Class1.csv', 'a')
myFile.write("Class = ")
myFile.write(MyClass + " ")
myFile.write("Name = ")
myFile.write(name + " ")
myFile.write("Score = ")
myFile.write(str(score) + " ")
myFile.write("\n")
myFile.close()
elif MyClass == "2":
myFile = open('Class2.csv', 'a')
myFile.write("Class = ")
myFile.write(MyClass + " ")
myFile.write("Name = ")
myFile.write(name + " ")
myFile.write("Score = ")
myFile.write(str(score) + " ")
myFile.write("\n")
myFile.close()
elif MyClass == "3":
myFile = open('Class3.csv', 'a')
myFile.write("Class = ")
myFile.write(MyClass + " ")
myFile.write("Name = ")
myFile.write(name + " ")
myFile.write("Score = ")
myFile.write(str(score) + " ")
myFile.write("\n")
myFile.close()
this code is for saving the class into the decided file and the code below is for deciding which class they are in
def classes():
#here its asking the question to the user
theClass = input ("What class are you in: 1,2,3 ")
# Test the input is between 1 and 3
while (int(theClass) > 3):
theClass = input ("Sorry, please enter a number between 1 and 3 ")

pulling numbers out of text

I have a text file that has results listed like this:
Welcome to your results
The result of 50+25=75
The result of 60+25=85
The result of 70+25=95
The result of 80+25=105
I need python to read the file and pull out the numbers to the left of the "=" and add them up. I have no idea how to get this to work.
# take input from the user
print("Select operation.")
print("1.Display The Content of the result file")
print("2.Add two numbers")
print("3.Subtract two numbers")
print("4.Multiply two numbers")
print("5.Divide two numbers")
print("6.Append results to file")
print("7.Display Total of inputs")
print("8.Display Average of inputs")
print("9.Exit")
choice = input("Select an option(1-9):")
if choice == 1:
file = open('results.txt', 'r')
print file.read()
elif choice >= 2 and choice <= 5:
l_range = int(input("Enter your Lower range: "))
h_range = int(input("Enter your Higher range: "))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 < l_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
elif num2 > h_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
else:
if choice == 2:
print "The result of", num1,"+", num2,"=", add(num1,num2)
resultstr = "The result of " + str(num1) + "+" + str(num2) + "=" + str(add(num1,num2))
elif choice == 3:
print "The result of", num1,"-",num2,"=", subtract(num1,num2)
resultstr = "The result of " + str(num1) + "-" + str(num2) + "=" + str(subtract(num1,num2))
elif choice == 4:
print "The result of", num1,"*", num2,"=", multiply(num1,num2)
resultstr = "The result of " + str(num1) + "*" + str(num2) + "=" + str(multiply(num1,num2))
elif choice == 5:
print "The result of", num1,"/", num2, "=", divide(num1,num2)
resultstr = "The result of " + str(num1) + "/" + str(num2) + "=" + str(divide(num1,num2))
if num2 == 0:
print "The result of", num1,"/", num2, "=", "You can't divide by zero!"
elif choice == 6:
print("The results have been appended to the file")
file = open('results.txt', 'a')
file.write(resultstr + "\n")
file.close()
elif choice == 7:
print ("Display total inputs")
elif choice == 8:
print ("Display average of total inputs")
elif choice == 9:
print ("Goodbye!")
else:
print("Invalid input")
lp_input = raw_input("Do you want to perform another action? Y/N:")
if lp_input == 'n':
print("Goodbye!")
From what I understand from the question, a simple regex match would solve the problem. You may do it like so:
Read the file line by line.
Make a regex pattern like so, to get the data from the string:
>>> pattern = "The result of (\d+?)[+-/*](\d+?)=(\d+).*"
Say if a line from the file is stored in the variable result:
>>> result = "The result of 25+50=75"
import the re library and use the match function like so which gives you the data from the string:
>>> s = re.match(pattern, result)
>>> print s.groups()
('25', '50', '75')
You can then get the numbers from this tuple and do any operation with it. Change the regex to suit your needs, but given the contents of the file at the start, this should be fine.

Not decrypting what I have encrypted [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having an issue with my decryption algorithm. It outputs to a text file a huge list of repeated ((((( and other things. What's wrong with my code, and how can I fix it? I think it has something to do with the last function of the decrypting process. But I am not sure.
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&()-_=+[]{}\\|;:\'",./<>?\n\t '''
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (evenChars >(oddChars)):
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
for ch in text: #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(ch)
else:
oddNums.append(ch)
index += 1
decrypted= []
if (evenNums >(oddNums)):
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line + "\n"
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
matrices = getMatrices(text)
for value in matrices:
encrypted_file.write(str(value) + "\n")
encrypted_file.close()
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()
Well this was a fun one!
in def convertToNum(ch): the alpha does not equal the alpha in def outPutString(text): (missing an *) causing (in my case) tabs instead of spaces and a ? to appear at the end of my decrypted string. I would recommend using a global variable to prevent things like this happening in the future.
Your encryption algorithm worked great and didn't need any adjustment. There were some incompatible variable types in the decryption phase but I managed to get everything to work and have included the working code (my comments marked with ##) I hope this helped.
Edit: As Eric points out in the comments, if (evenNum>(oddNum)) is probably not doing what you want it to do. According to the python docs:
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
I Assume you want to compare the lengths of the two arrays to make sure they are equal. If this is the case then you would want to use if (len(evenNum)>len(oddNum))
import sys
import os.path
def convertToNum(ch):
alpha ='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t ''' #you forgot your asterix
index = alpha.find(ch)
return index
def Matrix(text):
evenChars = []
oddChars = []
index = 0
for ch in text:
if index % 2 == 0:
#this is an even character
evenChars.append(convertToNum(ch))
else: #this is an odd character
oddChars.append(convertToNum(ch))
index += 1
masterList = []
if (len(evenChars) >len(oddChars)): ## comparing lengths instead of contents
oddChars.append(convertToNum(" "))
for i in range(len(evenChars)):
masterList.append([evenChars[i],oddChars[i]])
return masterList
def getMatrices(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
indList = Matrix(text)
encryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
encryptList.append(x*a + y*c)
encryptList.append(x*b + y*d)
return encryptList
def backtoText(text):
print("A list of integers acts as a key. Each value is stored in a,b,c,d. If you have already entered a key to encrypt, please use the same key. Please enter the values for: ")
a = int(input("\nA :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
if (a*d) - (c*b) == 1:
print("Valid Key\n")
elif (a*d) - (c*b) ==-1:
print("Valid Key\n")
else:
print("Invalid Key")
sys.exit()
keyA = ((a*d) - (c*b)) * (d)
keyB = ((a*d) - (c*b)) * (-b)
keyC = ((a*d) - (c*b)) * (-c)
keyD = ((a*d) - (c*b)) * (a)
print(keyA,keyB,keyC,keyD)
evenNums=[]
oddNums=[]
index = 0
newText = text[0].strip('[ ]') ## these two lines convert the string to an array
textArray = newText.split(',')
for ch in textArray: ## changed text to textArray(see above) #ch takes the place of the next characer in plain text
if index % 2 == 0:
evenNums.append(int(ch)) ## converting string number to int for later operations
else:
oddNums.append(int(ch))
index += 1
decrypted= []
if (len(evenNums) >len(oddNums)): ## comparing lengths instead of arrays
oddNums.append(" ")
for i in range(len(evenNums)):
decrypted.append([evenNums[i],oddNums[i]])
indList = decrypted
decryptList = []
for nestList in indList:
x = nestList[0]
y = nestList[1]
decryptList.append(x*keyA + y*keyC)
decryptList.append(x*keyB + y*keyD)
return decryptList
def outPutString(text):
alpha = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!##$%^&*()-_=+[]{}\\|;:\'",./<>?\n\t '''
finalString =''
text = backtoText(text)
for ch in text:
finalString += alpha[ch]
print(finalString)
return finalString
def main():
print("What would you like to do?: ")
answer = input("1) Encrypt File\n2) Decrypt File\n\n")
if answer == '1':
fileName = input("Please enter a filename to encrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
plaintext_file = open(fileName)
text = ""
for line in plaintext_file.readlines():
text += line ##+ "\n" ##you don't need to add a new line as '\n' is already included at the end of every line.
plaintext_file.close()
name =input("Please enter the file name that you want to save the encrypted file as : ")
if os.path.isfile(name) == False:
##matrices = getMatrices(text)
##for value in matrices:
##encrypted_file.write(str(value) + "\n")
##encrypted_file.close()
## I added the line below(and removed lines above) to be consistent with your later usage
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
encrypted_file = open(name,'w')
encrypted_file.write(str(getMatrices(text)))
encrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
elif answer == '2':
fileName = input("Please enter a filename to decrypt : ")
if not os.path.isfile(fileName):
print("Invalid Entry. Computer will self destruct in 10 seconds\n\n")
sys.exit()
Encrypted_file = open(fileName)
text = []
for line in Encrypted_file.readlines():
text.append(line)
Encrypted_file.close()
name = input("Please enter the file name that you want to save the decrypted text saved as : ")
if os.path.isfile(name) == False:
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif os.path.isfile(name) == True:
answer2 = input("The file already exists. Would you like to overwrite it? >> Type y/n >> ")
if answer2 == 'y':
Decrypted_file = open(name,'w')
Decrypted_file.write(str(outPutString(text)))
Decrypted_file.close()
elif answer == 'n':
print("Thank you for wasting time :D \n\n")
sys.exit()
else:
print("Invalid response. It's not hard to put y or n.\n\n")
sys.exit()
else:
print("Invalid Entry. The program will terminate")
sys.exit()
main()

Categories