Remove Bottom 3 scores in file - python

numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
file = open("scores.txt","w")
for loop in range(numberofbands):
name = input("\nEnter the name of the band: ")
votes = input("Enter how many votes that band received: ")
file.write(name + "," + votes + "," + "\n")
file.close()
number_of_lines = len(open("scores.txt").readlines( ))
def removebottom3():
#code to remove bottom 3 here
removebottom3()
The first part writes the band's name and score to the file.
I want the code to remove the lowest 3 scoring bands from the file. There will be a function for that.
How can I do this?
Thanks in advance.

You are quite off. Let me help you.
First, consider using Counter, it is meant for this kind of cases.
Second, try dividing the script logic into blocks (divide and conquer!), first get the data, then sort and remove the last 3, and only at the end write the results to a file.
Here is an example of the implementation.
from collections import Counter
numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
scores = Counter()
for n in range(numberofbands):
name = input("\nEnter the name of the band: ")
vote = input("Enter how many votes that band received: ")
scores.update({name:int(votes)})
#remove the last 3
final = scores.most_common()[:-3]
#write to file
with open('scores.txt', 'w') as f:
for name, vote in final:
f.write(f'{name},{vote}\n')

since you are already reading all the lines from the file,
number_of_lines = len(open("scores.txt").readlines( ))
you can use sorted to sort your lines by score,
lines = open("scores.txt").readlines()
sorted(lines,
key=lambda x : float(x.split(",")[1]),
reverse = True)

Related

Python - searching for letters in a list of words

I am absolutely new to programming atm. I have searched the forums but none of the results were applicable to my case (unless I am mistaken, but trust me the first thing I did was to google). Please help me if you have time.
Write a python program that prompts the user to enter a list of first names and stores them in a list. The program should display how many times the letter 'a' appears within the list.
Now I thought I have got the PERFECT code. But everytime the program only counts the number of "a"s in the first word on the list!?
terminate = False
position = 0
name_list = [ ]
while not terminate:
name = str(input('Please enter name: '))
name_list.append(name)
response = input('Add more names? y/n: ')
if response == 'n':
terminate = True
print(name_list)
for t in name_list:
tally = name_list[position].count('a')
position = position + 1
print("The numer of 'a' is: ", tally)
If anyone has time to help I would appreciate it.
A couple of points:
you meant to use tally as an accumulator but are actually not adding to it.
You don't need the position indexer, for t in name_list already iterates over all names in the list, at each iteration of the for loop t is a name from name_list.
fix the inner loop
terminate = False
# position = 0 <-- this is not needed anywhere
name_list = [ ]
while not terminate:
name = str(input('Please enter name: '))
name_list.append(name)
response = input('Add more names? y/n: ')
if response == 'n':
terminate = True
print(name_list)
tally = 0 # initialise tally
for t in name_list:
tally += t.count('a') # increment tally
print("The numer of 'a' is: ", tally)
Your code is not fully understandable to me. Probably, because some stuff is missing. So, I am assuming, you already have the list of names. In the code you presented, you are overwriting tally each time you count the number of a in a name in the list. Besides other possible bugs in your code (maybe when creating the list of names - I'd use a while-loop for this), you should write
tally += name_list[position].count('a')
which equals
tally = tally + name_list[position].count('a')
instead of your
tally = name_list[position].count('a')
terminate = False
position = 0
name_list = [ ]
tally = 0
while not terminate:
name = str(input('Please enter name: '))
name_list.append(name)
response = input('Add more names? y/n: ')
if response == 'n':
terminate = True
print(name_list)
for t in name_list:
#tally = name_list[position].count('a')
tally += name_list[position].count('a')
position = position + 1
print("The numer of 'a' is: ", tally)
initilize tally=0 and insted of "tally = name_list[position].count('a')" use "tally += name_list[position].count('a')" if you have to count "a" in entire list you have to update the tally value
I would suggest you get rid of the for loop, and position counter. If you want the total of all 'a', you have to sum tally for all the names :
terminate = False
name_list = []
total = 0
while "Adding more names":
name = str(input('Please enter name: '))
name_list.append(name)
tally = name.count('a')
total += tally
print("The numer of 'a' in current name is: ", tally)
if input('Add more names? y/n: ') == 'n':
break
print(name_list)
print("The numer of 'a' is: ", total)

Python - Writing to a specific point in a line

I have encountered an error when writing my program and would like some help with it. The program has to replace a specific segment of the line with a calculated value. The segment in which I am talking about is the third index in a line, formatted like this:
Product01, 12346554, 15, 6
I am having the program calculate the value in which I want to replace with the final value but no matter how much I seem to try, my code frequently gives errors. For an example, I have used seek to try and move the cursor to allow myself to edit this value, however with the following code:
Total = 0
receipt = open("Receipt.txt", "w")
while True:
try:
Prod_Code = input("Enter a code or Done to get your final receipt: ")
if len(Prod_Code) == 8:
int(Prod_Code)
with open("Data Base.txt", "r+") as searchfile:
for line in searchfile:
if Prod_Code in line:
print(line)
Quantity = input("What quantity of this product do you want? ")
Total += float(line.split(",")[2]) * int(Quantity)
print(Quantity)
print(Total)
receipt.write(line)
print(line.split(",")[3])
W = int(line.split(",")[3]) - int(Quantity)
print(W)
L = (line)
L.seek(27, 0)
L.write(str(W))
elif Prod_Code == "Done":
receipt.close()
with open("Receipt.txt", "r") as datafile:
for item in datafile:
print(item.split(",")[1])
print(item.split(",")[2])
print("Your total cost is £", Total)
input("Press Enter to exit:")
exit()
else:
print("Incorrect length, try again")
except ValueError:
print("You must enter an integer")
However, when I run it this is the error that I get:
AttributeError: 'str' object has no attribute 'seek'.
I was wondering if anyone could help, and/or provide a different answer to my problem? Thanks in advance.

Python Lists: .lower() attribute error

I am trying to create a program on python to do with manipulating lists/arrays. I am having trouble with an error:
lowercase = names.lower
AttributeError: 'list' object has no attribute 'lower'
I really need some help to fix this!
names = [] #Declares an array
print("Type menu(), to begin")
def menu():
print("----------------------------MENU-----------------------------")
print("Type: main() for core functions")
print("Type: delete() to delete a name")
print("Type: save() to save the code")
print("Type: load() to load the saved array")
print("Type: lower() to make all items in the list lower case")
print("-------------------------------------------------------------")
def main():
times = int(input("How many names do you want in the array? ")) #Asks the user how many names they want in the array
for i in range(times):
names.append(input("Enter a name ")) #Creates a for loop that runs for the amount of times the user requested, it asks the user to enter the names
choice = input("Would you like the array printed backwards? ") #asks the user whether they want the array backwards
if choice == "Yes":
names.reverse() #If the user says yes, the array is reversed then printed backwards
print(names)
else:
print(names) #Otherwise, the array is printed normally
number = int(input("Which item would you like to print out? "))
number = number - 1
print(names[number])
start = int(input("What is the first position of the range of items to print out? "))
start = start - 1
end = int(input("What is the last position of the range of items to print out? "))
print(names[start:end])
def delete():
takeAway = input("Which name would you like to remove? ")
names.remove(takeAway)
print(names)
def save():
saving1 = open("Save.txt", 'w')
ifsave = input("Would you like to save the array? ")
if ifsave == "Yes":
for name in names:
saving1.write("%s\n" % name)
saving1.close
else:
menu()
def load():
loadquestion = input("Would you like to load a list of names? ")
if loadquestion == "Yes":
saving1 = open('Save.txt', 'r')
print(saving1.read())
saving1.close()
else:
menu()
def lower():
lowerq = input("Would you like to make the array lowercase? ")
if lowerq == "Yes":
lowercase = names.lower
print(lowercase)
else:
menu()
The variable names is a list. You can't use the .lower() method on a list.
pp_ provided the solution:
lowercase = [x.lower() for x in names]
While not exactly equivalent to the previous example, this may read better to you and has, effectively, the same result:
lowercase=[]
for name in names:
lowercase.append(name.lower())
Alternate solution that may fit your needs:
print (str(names).lower())
Like the error message says, you can't use .lower() on lists, only on strings. That means you'll have to iterate over the list and use .lower() on every list item:
lowercase = [x.lower() for x in names]

Writing Data to a .txt File

I am trying to write data to a text file in python and I am trying to get the user to choose the name of the file as a string. However when it comes to actually writing the data, it shows an error.
import random
name = input("Please enter your name: ")
clas = input("Please enter what class you are in: ")
#Uses a list to show the 3 operators I want to use
ops = ['+', '-', '*']
#Defines two variables as 1 and 0
x = 1
score = 0
#While the variable x is less than or equal to 10, the loop will continue
while x <= 10:
#Selects 2 random integers from 1 to 10
num1 = random.randint(1,10)
num2 = random.randint(1,10)
#Choses the operation from the list `ops`
operation = random.choice(ops)
#Prints the 2 numbers and operation in an arithmetic question layout
print(num1,operation,num2)
maths = int(eval(str(num1) + operation + str(num2)))
#Gets the user to input there answer to the question
answer = int(input("What is the answer to that arithmetic question? "))
#If the answer the user input is equal to the correct answer the user scores a point and is told it is correct
#Otherwise, the answer must be wrong so the user is told his score is incorrect and that no points are scored
if answer == maths:
print ("Correct")
score += 1
else:
print ("Incorrect Answer")
#Add one onto the score that the while loops depends on to make sure it only loops 10 times
x = x + 1
#Leaves the iteration after 10 loops and prints the users final score
print ("You scored", score, " out of 10 points")
score2 = str(score)
score = str(name + score2 + "\n")
with open(clas."txt", "a") as scorefile:
scorefile.write(score)
To write to a file:
f = open("filename.txt","w")
f.write("Writing to a file!")
# writes "Writing to a file!" as a new line in filename.txt
f.close()
To read a file:
f = open("filename.txt","r")
lines = f.readlines()
f.close()
print lines
# prints array
Make sure to use f.close(), otherwise bad things will happen.

My loop and File I/O

How do I get my loop to write to the file until I stop the loop?
For example
outFile = "ExampleFile.txt", "w"
example = raw_input(" enter number. Negative to stop ")
while example >= 0:
example = raw_input("enter number. Negative to stop")
outFile.write("The number is", example,+ "\n")
I feel like im hitting it close but I'm not sure. I wasn't sure how to search for this question in paticular. Sorry, I keep getting a error stating that the function takes 1 argument, when I enter more than 2.
import os.path
outFile = open("purchases.txt","w")
quantity = float(raw_input("What is the quantity of the item :"))
cost = float(raw_input("How much is each item :"))
while quantity and cost >= 0:
quantity = float(raw_input("What is the quantity of the item :"))
cost = float(raw_input("How much is each item :"))
total = quantity * cost
outFile.write("The quantity is %s\n"%(quantity))
outFile.write("the cost of the previous quality is $s\n" %(cost))
outFile.close()
outFile = open("purchases.txt","a")
outFile.write("The total is ",total)
outFile.close()
when you write:
outFile = "ExampleFile.txt", "w"
you create a tuple, not a file object.
You probably meant to write:
outFile = open('ExampleFile.txt','w')
Of course, you could do this a little better using a context manager:
with open('ExampleFile.txt','w') as outFile:
#...
Your code has a second error:
outFile.write("The number is", example,+ "\n")
baring the SyntaxError (,+), file.write takes only 1 argument. You probably wanted something like:
outFile.write("The number is {0}\n".format(example))
or using the old style of string formatting (as requested):
outFile.write("The number is %s\n"%(example))

Categories