Sorting a file numerically - python

I am new to python and trying to create a maths quiz program towards the end of the program I want to be able to print all the results in the file ( stored in the variable Reverseinfo) in numerical order. This doesn't seem to work , regardless of if I use the .sort function or the sorted() function. Any help would be appreciated, thanks
ReverseInfo already has scores and names put into the file
ReverseInfo= (score + (" ") + Name)
ClassANum=open("Class A Results High to Low.txt","a")
ClassANum.write(ReverseInfo)
ClassANum.write(" \n")
ClassANum.close()
ClassBNum=open("Class B Results High to Low.txt","a")
ClassBNum.write(ReverseInfo)
ClassBNum.write(" \n")
ClassBNum.close()
ClassCNum=open("Class C Results High to Low.txt","a")
ClassCNum.write(ReverseInfo)
ClassCNum.write(" \n")
ClassCNum.close()
if Viewscores=="Y":
Classresults=input("Which Class would you like to see the results of?")
if Classresults=="A":
ClassA=open("Class A Results.txt","r")
Class=ClassA
alphabet=ClassA.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="B":
ClassB=open("Class B Results.txt","r")
Class=ClassB
alphabet=ClassB.readlines()
for line in sorted(alphabet):
print(line)
elif Classresults=="C":
ClassC=open("Class C Results.txt","r")
Class=ClassC
alphabet=ClassC.readlines()
for line in sorted(alphabet):
print(line)
else:
print ("That is not valid")
Numerical=input(" Do you want to see the results alphabetically?")
if Numerical=="Y":
NumClassresults=input("Which Class would you like to see the results of?")
if NumClassresults=="A":
ClassA=open("Class A Results High to Low.txt","r")
Class=ClassA
Hightolow=ClassA.readlines()
for line in sorted(Hightolow):
print(line)
elif NumClassresults=="B":
ClassA=open("Class B Results High to Low.txt","r")
Class=ClassB
Hightolow=ClassB.readlines()
for line in sorted(Hightolow):
print(line)
if NumClassresults=="C":
ClassA=open("Class C Results High to Low.txt","r")
Class=ClassC
Hightolow=ClassC.readlines()
for line in sorted(Hightolow):
print(line)
the data stored in Class A is: 10 Jamie
8 Jamie
8 Peter
10 Ham
4 Jack
10 Joseph
9 jamie
9 Yuan
9 Bob
10 John
6 Nash
8 John
10 josh
10 Honey
there is currently nothing stored in Class b file
finally in class c:
9 jamie
9 Yuan
9 Bob
8 Peter
8 Jamie
4 Jack
10 Joseph
10 John
10 Jamie
10 Ham

Try below (assuming your file looks like Name 100 with many rows)
with open("Class C Results High to Low.txt","r") as f:
lines = [(int(line.split(" ")[0]), line.split(" ")[1]) for line in f.readlines()]
for l in sorted(lines, key=lambda score_name: score_name[0]):
print l
Please let me know if there are any syntax errors (leave a comment), I couldn't test this - on the phone at the moment.

If the file is just lines with one integer per line, Hightolow will be a list of strings (that can be passed to int)
You need to pass a key function to sorted (or sort). In this case int does exactly what you need.
sorted(Hightolow, key=int)
ie use it in the loop like this:
for line in sorted(Hightolow, key=int):
Alternatively you can make Hightolow a list of ints as you read the file
Hightolow = [int(x) for x in ClassA]

Related

Formatted strings, decimals and commas question

I have a .txt file that I read in and wish to create formatted strings using these values. Columns 3 and 4 need decimals and the last column needs a percent sign and 2 decimal places. The formatted string will say something like "The overall attendance at Bulls was 894659, average attendance was 21,820 and the capacity was 104.30%’
the shortened .txt file has these lines:
1 Bulls 894659 21820 104.3
2 Cavaliers 843042 20562 100
3 Mavericks 825901 20143 104.9
4 Raptors 812863 19825 100.1
5 NY_Knicks 812292 19812 100
So far my code looks like this and its mostly working, minus the commas and decimal places.
file_1 = open ('basketball.txt', 'r')
count = 0
list_1 = [ ]
for line in file_1:
count += 1
textline = line.strip()
items = textline.split()
list_1.append(items)
print('Number of teams: ', count)
for line in list_1:
print ('Line: ', line)
file_1.close()
for line in list_1: #iterate over the lines of the file and print the lines with formatted strings
a, b, c, d, e = line
print (f'The overall attendance at the {b} game was {c}, average attendance was {d}, and the capacity was {e}%.')
Any help with how to format the code to show the numbers with commas (21820 ->21,828) and last column with 2 decimals and a percent sign (104.3 -> 104.30%) is greatly appreciated.
You've got some options for how to tackle this.
Option 1: Using f strings (Python 3 only)
Since your provided code already uses f strings, this solution should work for you. For others reading here, this will only work if you are using Python 3.
You can do string formatting within f strings, signified by putting a colon : after the variable name within the curly brackets {}, after which you can use all of the usual python string formatting options.
Thus, you could just change one of your lines of code to get this done. Your print line would look like:
print(f'The overall attendance at the {b} game was {int(c):,}, average attendance was {int(d):,}, and the capacity was {float(e):.2f}%.')
The variables are getting interpreted as:
The {b} just prints the string b.
The {int(c):,} and {int(d):,} print the integer versions of c and d, respectively, with commas (indicated by the :,).
The {float(e):.2f} prints the float version of e with two decimal places (indicated by the :.2f).
Option 2: Using string.format()
For others here who are looking for a Python 2 friendly solution, you can change the print line to the following:
print("The overall attendance at the {} game was {:,}, average attendance was {:,}, and the capacity was {:.2f}%.".format(b, int(c), int(d), float(e)))
Note that both options use the same formatting syntax, just the f string option has the benefit of having you write your variable name right where it will appear in the resulting printed string.
This is how I ended up doing it, very similar to the response from Bibit.
file_1 = open ('something.txt', 'r')
count = 0
list_1 = [ ]
for line in file_1:
count += 1
textline = line.strip()
items = textline.split()
items[2] = int(items[2])
items[3] = int(items[3])
items[4] = float(items[4])
list_1.append(items)
print('Number of teams/rows: ', count)
for line in list_1:
print ('Line: ', line)
file_1.close()
for line in list_1:
print ('The overall attendance at the {:s} games was {:,}, average attendance was {:,}, and the capacity was {:.2f}%.'.format(line[1], line[2], line[3], line[4]))

Python Error: IndexError: string index out of range for a Family Tree Program

So I'm making this family tree program thing, I've got two files:
FamNames.txt
Nerk,Sam,M,1
Nerk,Aileen,F,2
Nerk,Peter,M,3
Smith,Cathy,F,5
Nerk,Matthew,M,7
Nerk,Janine,F,21
Martin,Marion,F,22
Nerk,Louise,F,8
Nerk,Melissa,F,9
Nerk,Kim,F,10
Nerk,Luke,M,11
Smith,Greg,M,12
Smith,Marta,F,17
Smith,Isaac,M,18
Nerk,Eliza,F,19
Nerk,Henry,M,20
Nerk,Karina,F,28
and ParentChild.txt
1,8
1,9
1,10
1,11
2,1
2,5
2,7
3,1
3,5
3,7
12,17
12,18
5,17
5,18
7,19
7,20
28,19
28,20
22,8
22,9
22,10
27,21
21,11
FamNames stores the Lastname, Firstname, Gender, ID
ParentChild store the ID of parent, ID of child
Heres my code for finding the child of anyone the user wants:
#Create empty arrays
LastName = []
FirstName = []
Gender = []
ID = []
ParentID = []
ChildID = []
#Assign the correct data to the arrays
import csv
f = open('FamNames.txt')
for row in csv.reader(f):
LastName.append(row[0])
FirstName.append(row[1])
Gender.append(row[2])
ID.append(row[3])
f.close()
f = open('ParentChild.txt')
for row in csv.reader(f):
ParentID.append(row[0])
ChildID.append(row[1])
f.close()
#Prints out the first and last names of everyone with a line number infront
n = 0
while n < 17: #number of lines in FamNames.txt
print('Line', n, FirstName[n], LastName[n])
n = n + 1
#User selects who they want to view family members of
i = int(input("\nPlease type in line number for whom you'd like to see the family members:\n"))
print("\nYou've selected to see the family members of:", FirstName[i], LastName[i])
#Finds the line on which the ID is located in ParentChild.txt
ID = ID[i]
t = 0
while t < 23: #number of lines in ParentChild.txt
if ID == ParentID[t]: #n will store the line on which the parent is
break
t = t + 1
#Finds the line on which the child is located in FamNames.txt
child = ChildID[t]
x = 0
while x < 17: #number of lines in FamNames.txt
if child == ID[x]: #n will store the line on which the child is
break
x = x + 1
#Prints out the childs name
print('The child of', FirstName[i], LastName[i], 'is:', FirstName[x], LastName[x])
Heres the output/error:
Line 0 Sam Nerk
Line 1 Aileen Nerk
Line 2 Peter Nerk
Line 3 Cathy Smith
Line 4 Matthew Nerk
Line 5 Janine Nerk
Line 6 Marion Martin
Line 7 Louise Nerk
Line 8 Melissa Nerk
Line 9 Kim Nerk
Line 10 Luke Nerk
Line 11 Greg Smith
Line 12 Marta Smith
Line 13 Isaac Smith
Line 14 Eliza Nerk
Line 15 Henry Nerk
Line 16 Karina Nerk
Please type in line number for whom you'd like to see the family members:
0
You've selected to see the family members of: Sam Nerk
Traceback (most recent call last):
File "U:\Subject\11\SDD\Family tree\FamilyTree.py", line 46, in <module>
if child == ID[x]: #n will store the line on which the child is
IndexError: string index out of range
I don't know why says the index is out of range, it should be breaking out of the while loop once x = 7 (as the child Id should be equal in line 7).
Please excuse my amateurish code, I literally just started learning python, any help would be appreciated on why I'm getting this error :)
This line is breaking your logic:
#Finds the line on which the ID is located in ParentChild.txt
ID = ID[i]
You should assign this value to a unique variable name as it's already used to declare an array of Id's earlier in the program.
You are essentially overwriting it's list of values.
#Finds the line on which the ID is located in ParentChild.txt
unique_ID = ID[i]
Try renaming it like above example and renaming any other reference to the variable.

Formatting data in a text file using Python

I am fairly new to python and I am creating a program to try and take data from a text file, The quiz has 10 questions, and the name and scores of the users are saved in a text file. This is what the text file looks like:
Bob - 7
Steve - 4
Jake - 10
The idea is if the person tries again and gets another score, the program will realise the user already has data in the file, and it will be appended as such:
Bob - 7, 8, 3
The user can only save a maximum of 3 scores, e.g. If Bob tries again and gets a 10, the 7 will be removed and the 8 and 3 move one place forward like this:
Bob - 8, 3, 10
Then as an option, all the names and scores need to be read back in and placed in order of score with their names attached, If anyone could help that would be greatly appreciated.
Here is the code:
import random, time, re
name = input("Welcome, please type your name to continue: ")
class_number = input("What class are you in? (1, 2 or 3)")
class_number = ("H:\A453\\Class_"+class_number+".txt")
print("\nThank you", name, "you will now answer a short series of questions..\n")
score_counter = 0
x = 1
The Questions come here.... score_counter + 1 if correct etc..
f = open(class_number,"r")
contents = f.read()
items = re.findall(str(name+".*$"),contents,re.MULTILINE)
for y in items:
username, score = y.split(' - ')
print(username, score)
The part that adds the score to the database is here, but I have omitted it as I have yet to complete the bit above ^
f = open(class_number,"r")
f.write(str(name)+" - "+str(score_counter))
f.close()
Any help would be greatly appreciated, also I am not sure how to fix the problem of if for instance the user's name is Bob, and in the text file there is:
Bobby - 9
It will pull up Bobby's score instead, a fix for this would also be great.
Jake

Import a file and putting it inside a tuple in a particular format (python)

I am really stuck on this code that i've been working on and for 9 hours straight I cannot get it to work. Basically I am importing a file and splitting it to read the lines one by one and one of the tasks is to rearrange the lines in the file, for example the first line is: 34543, 2, g5000, Joseph James Collindale should look like : ['Collindale, Joseph James', '34543', g5000', '2']. So essentially it should loop over each line in the file and rearrange it to look like that format above. I created a function to check whether the length of the line is either 5 or 6 because they would both have a different format.
def tupleT(myLine):
myLine = myLine.split()
if len(myLine) == "5":
tuple1 = (myLine[4],myLine[3],myLine[0],myLine[2],myLine[1])
return tuple1
elif len(myLine) == "6":
tuple1 = (myLine[5],myLine[3]+ myLine[4],myLine[0],myLine[2], myLine[1])
return tuple1
mylist = []
x = input("Enter filename: ")
try :
f = open(x)
myLine = f.readline()
while (len(myLine)>0):
print(myLine[:-1])
myLine = f.readline()
tupleT(myLine)
f.close()
except IOError as e :
print("Problem opening file")
This is what the original file looks like in textpad and its called studs.txt:
12345 2 G400 Bart Simpson
12346 1 GH46 Lisa Simpson
12347 2 G401 Homer J Simpson
12348 4 H610 Hermione Grainger
12349 3 G400 Harry Potter
12350 1 G402 Herschel Shmoikel Krustofski
13123 3 G612 Wayne Rooney
13124 2 I100 Alex Ferguson
13125 3 GH4P Manuel Pellegrini
13126 2 G400A Mike T Sanderson
13127 1 G401 Amy Pond
13128 2 G402 Matt Smith
13129 2 G400 River Storm
13130 1 H610 Rose Tyler
Here is some commented code to get you started. Your code was a bit hard to read.
Consider renaming first, second and third since I have no idea what they are...
#!/usr/bin/env python
# this is more readable since there are actual names rather than array locations
def order_name(first, second, third, first_name, middle_name, last_name=None):
if not last_name:
# if there is no last name we got the last name in middle name (5 arguments)
last_name = middle_name
else:
# if there is a middle name add it to the first name to format as needed
first_name = "%s %s" % (first_name, middle_name)
return ("%s, %s" % (last_name, first_name), first, third, second)
with open('studs.txt') as o:
# this is a more standard way of iterating file rows
for line in o.readlines():
# strip line of \n
line = line.strip()
print "parsing " + line
# you can unpack a list to function arguments using the star operator.
print "ordered: " + str(order_name(*line.split()))

Search user input from a string and print

I have a string called new_file that I read from a file with these contents:
;ASP718I
;AspA2I
;AspBHI 0 6 9 15 ...
;AspCNI
;AsuI 37 116 272 348
...
I am using name = raw_input ("enter the enzyme ")
to get data from the user and I am trying to print the corresponding fields from the above file (new_file).
For the input ;AspBHI I'd like the program to print the corresponding line from the file:
;AspBHI 0 6 9 15 ...
How can I achieve this?
This is a start:
db = dict((x.split(" ")[0], x) for x in new_file.split("\n"))
name = raw_input("enter the enzyme ")
print db[name]
Also try to be nice next time, people might help you with more enthusiasm and even explain their approach.

Categories