How format my data in category in python - python-3.x

a python program to read the rainfall.txt file and then write out a new file
called rainfallfmt.txt . The data should be grouped on the total annual rainfall field into
the following categories: [60-70], [71-80], [81-90],[91-]. Under each category, the new
file should format each line so that the city is right-justified in a field that is 25 characters wide, and the rainfall data should be printed in a field that is 5 characters wide with 1 digit to the right of the decimal point.
This is what I have so far;
the problem is I don't know how to categorize it?
Would you please help me and let me know how I can solve this problem?
================================================
# read the rainfall.txt then write out a new file called rainfall.txt
# the data should be grouped on the total annual rainfall field into the
# categories: [60-70], [71-80], [81,90], [91-]
import os.path
def main():
endofprogram = False
try:
InputFileName = input('Enter name of input file: ')
infile = open(InputFileName,'r')
OutputFileName = input('Enter name of output file: ')
# determine wether name exists
while True:
if os.path.isfile(OutputFileName):
OutputFileName = input('File Exists. Enter name again: ')
else:
outfile = open(OutputFileName,'w')
break
except IOError:
print("Error opening file - End of program")
endofprogram = True
#If there is not exception, start reading the input file
#Write the same data in formated form in new file.
if endofprogram == False:
data = []
for line in infile:
.
.# I dont know what to do in here!
.
outfile.write(data[0])
main()

# read the rainfall.txt then write out a new file called rainfall.txt
# the data should be grouped on the total annual rainfall field into the
# categories: [60-70], [71-80], [81,90], [91-]
import os.path
def main():
endofprogram = False
try:
InputFileName = input('Enter name of input file: ')
infile = open(InputFileName,'r')
OutputFileName = input('Enter name of output file: ')
# determine wether name exists
while True:
if os.path.isfile(OutputFileName):
OutputFileName = input('File Exists. Enter name again: ')
else:
outfile = open(OutputFileName,'w')
break
except IOError:
print("Error opening file - End of program")
endofprogram = True
#If there is not exception, start reading the input file
#Write the same data in formated form in new file.
if endofprogram == False:
cat_60 = []
cat_71 = []
cat_81 = []
cat_91 = []
for line in infile:
city, rain = line.split(' ')
rain = float(rain)
if 60 <= rain < 70:
cat_60.append((city, rain)) # Storing a tuple in the list
elif 70 <= rain < 80:
cat_71.append((city, rain))
elif 80 <= rain < 90:
cat_81.append((city, rain))
elif 90 <= rain :
cat_91.append((city, rain))
outfile.write("[60-70]"+'\n')
for i in range(len(cat_60)):
city = cat_60[i][0]
rain = cat_60[i][1]
outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
outfile.write("[70-80]"+'\n')
for i in range(len(cat_71)):
city = cat_71[i][0]
rain = cat_71[i][1]
outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
outfile.write("[80-90]"+'\n')
for i in range(len(cat_81)):
city = cat_81[i][0]
rain = cat_81[i][1]
outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
outfile.write("[91-]"+'\n')
for i in range(len(cat_91)):
city = cat_91[i][0]
rain = cat_91[i][1]
outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
main()

You can use split to separate the line in fields (it returns a list of strings), then take the rainfall, convert it to float, and use a list per category to store the data.
cat_60 = []
cat_71 = []
cat_81 = []
cat_91 = []
for line in infile:
city, rain = line.split(' ') # Spliting using blank as separator
rain = float(rain)
if 60 <= rain <= 70: # This works in Python as expected but don't in most other languages
cat_60.append((city, rain)) # Storing a tuple at the end of the list
elif 71 <= rain <= 80:
cat_71.append((city, rain))
# etc...
After that you can iterate in the categories and format the output with str.format() or using the % operator.
There are other things you can do to make your code more Pythonic, for example variable names should be snakecase, names in titlecase should be reserved for classes and uppercase for constants and instead of using a flag variable you can use and exit() to end the program.
You can do the following to call main() only if the file is invoked as a script:
if __name__ == '__main__':
main()

Related

How to read, write and update of your game highscore in pygame from/to file.txt saved.?

I am beginner who just copy a game sample from a book. The game working fine, and i able to understand all part of the exclude the read, write part.
The book didn't explain how it work and i been stuck at this part.
p/s: the game work totally fine. Just unable to write and read from highscore list.
def update_high_scores():
global score, scores
filename = r"/Users/User/Desktop/python/python-games/baloon fight/High-Score1.txt"
scores = []
with open(filename, "r") as file:
line = file.readline()
high_scores = line.split()
for high_score in high_scores:
if(score > int(high_score)):
scores.append(str(score) + " ")
score = int(high_score)
else:
scores.append(str(high_score) + " ")
with open(filename, "w") as file:
for high_score in scores:
file.write(high_score)
def display_high_scores():
screen.draw.text("HIGH SCORES", (350, 150), color="black")
y = 175
position = 1
for high_score in scores:
screen.draw.text(str(position) + ". " + high_score, (350, y), color="black")
y += 25
position += 1
I worked with your code, but updating it made the code more complicated. I thought it may be easier to provide a short function to update the score file.
The main steps:
Open the existing score file (scores are on single line separated by space)
Split the line and convert the scores to integers
If the current score is already included, just exit the function
Add the current score the score list
Sort the list and update the score file
Here is the code:
def update_high_scores():
global score, scores
filename = r"c:/tmp/High-Score1.txt" # file must exist
with open(filename, "r") as file:
line = file.readline() # scores are one line
high_scores = [int(s) for s in line.split()] # read scores as integers
if score in high_scores: # if current score already in high scores
return # no update needed
high_scores.append(score) # add current score
high_scores.sort() # sort scores (low - high)
with open(filename, "w") as file: # updates score file
for high_score in high_scores[::-1]: # write scores in reverse (high - low)
file.write(str(high_score) + " ")

Program: finding the percentage / hackerrank

I am using below python code:
n = int(input('enter the number:'))
student_marks = {}
for i in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input('enter the name:')
list_1 = list(student_marks[query_name])
no = len(l)
print(no)
s = sum(l)
print(s)
ss = s/no
print(ss)
But, i am getting an error while input the query_name during the run of code.
source: https://www.hackerrank.com/challenges/finding-the-percentage/problem
you can try to do
n = int(input('enter the number:'))
student_marks = {}
for i in range(n):
name, *line = input("enter name and scroe (spared by space): ").split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input('enter the name:')
list_1 = list(student_marks[query_name])
no = len(list_1)
print("the numer of scores {}".format(no))
s = sum(list_1)
print("The sum of all scores {}".format(s))
ss = s/no
print("The average score {}".format(ss))
if __name__ == '__main__':
n = int(input())
student_marks = {}
count = 0
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
for i in student_marks[query_name]:
count += i
average = count / len(student_marks[query_name])
print("%.2f" %average)
You can try this solution:
--------------------------
from decimal import Decimal
# Main function (like Java main() method)
if __name__ == '__main__':
# Taking number of times input will be taken from console and converting it into int type
n = int(input())
# creating an empty dictionary
student_marks = {}
# Iterate from: 0 to n-1 times
for _ in range(n):
# Taking the first argument as name and all other numbers inside line var
name, *line = input().split()
# Converting the numbers contained in line variable to a map then, converting into list
scores = list(map(float, line))
# Inserting into dictionary as key - value pair
student_marks[name] = scores
# Taking the student name from console and store into query_name
query_name = input()
# Fetch student marks using student name
query_scores = student_marks[query_name]
# Sum all the marks
total_scores = sum(query_scores)
# Find average of the marks
avg = Decimal(total_scores/3)
# print the average upto two decimal point
print(round(avg, 2))

How do I use a .csv file to create a dictionary and use it as a function?

I have a .csv file that I imported and basically what I need is to create a dictionary from the .csv file and use it along with my existing code. I want to be able to use it as a function and be able to call upon the new dictionary and its values when needed. Here is what I have so far:
csv file content:
Price Volume 52WeekHigh 52WeekLow DividendYield PE_Ratio
150.75 41.03 233.47 142 1.97% 12.34
98.65 3.23 114.55 87.54 1.60% 23.03
340.53 4.74 394.28 292.47 2.51% 19.03
129.77 4.2 173.24 112.06 2.68% 20.15
111.77 5.67 133.88 100.22 4.04% 14.8
111.42 8.73 120.2 97.68 1.61% 13.05
175.37 2.69 275.31 151.7 1.83% 12.31
177.89 4.72 215.43 158.09 2.37% 18.85
119.83 4.76 171.13 105.94 5.35% 18.65
47.74 22.75 57.5995 42.04 2.54% 14.44
code snippet
import csv
#import csv file.
invest_dict = 'DOW_Stock_short.csv'
with open(invest_dict , 'r') as invest_obj:
invest_dict = 'DOW_Stock_short.csv'
invest_reader = csv.reader(invest_obj)
result = {}
for row in invest_reader:
if invest_reader.line_num !=1:
key = row[0]
result[key] = row[1]
print(result)
print("The purpose of this project is to provide Stock Analysis by reading \n the data from a csv file and performing analysis on this data.")
def Greeting():
print(".........Welcome.............")
def Conversions(investment_amount):
investment_amount = float(investment_amount)
Euro = float(round(investment_amount / 1.113195,2) )
Pound = float(round(investment_amount / 1.262304,2) )
Rupee = float(round(investment_amount / 0.014316,2) )
print("The amount you invest in euro is: {:.2f}" .format(Euro) )
print("The amount you invest in pounds is: {:.2f}" .format(Pound) )
print("The amount you invested in Rupees is: {:.2f}" .format(Rupee) )
def minimum_stock():
key_min = min(result, key = (lambda k: result[k]))
print("The lowest stock you can buy is: ",result[key_min])
def maximum_stock():
key_max = max(result, key = (lambda k: result[k]))
print("The highest stock you may purchase is: ",result[key_max])
def invest_range(investment_amount):
new_list = []
new_list = [i for i in result if i > 50 and i < 600]
return(sorted(new_list))
answer = 'yes'
while answer:
print(Greeting())
try:
investment_amount = float(input("Please enter the amount you want to invest:$ "))
print("Thank you for investing:$ {:,.2f}".format(investment_amount))
except:
print("Please enter a valid amount...")
continue
print(Conversions(investment_amount))
for i in result:
i = investment_amount
if i <25:
print("Not enough funds to purchase stock")
break
elif i>25 and i <250:
print(minimum_stock())
break
elif i >= 250 and i <= 1000:
print(maximum_stock())
break
print("This is the range of stocks you may purchase: ", invest_range(investment_amount))
answer = input("Would you like to complete another conversion? yes/no " )
if answer == 'no':
print("Thank you for investing.")
break

A permanent list change(Save python file)

I am a noob in python and i need help.I have made a phonebook where you can add the contacts.But the problem is that when i exit the program the changes to the list are not saved.I want the user to be able to make permanent changes to the list.I have seen posts about a file=open("something",'w') code to do this(I think) but i dont know where to insert this code and i dont really understand what it is.Could someone help me understand what this is about..Here is the full code:
name = ["ranga","hari"]
number = [9895497777,9]
book = {name[0]:number[0],name[1]:number[1]}
def search():
print("Contacts:")
for x in book:
print(x,':',book[x])
while 1:
count = 0
a = 0
ch1 = input("search: ")
try:
ch1 = int(ch1)
except ValueError:
while a < len(name):
result = name[a].find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count = count + 1
if count == 0:
print("Not available.Try again")
continue
else:
break
ch1 = str(ch1)
while a < len(number):
sumber = str(number[a])
result = sumber.find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count += 1
if count == 0:
print("Not available.try again")
continue
else:
break
def add():
print("What is the name of the contact you want to add?")
name1 = input()
name.append(name1)
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
number.append(number1)
book[name1] = number1
break
def remoe():
print("Reference:")
for x in book:
print(x,':',book[x])
while 1:
print("What is the name of the contact you want to remove?")
name2 = input()
if name2 in book:
increment = name.index(name2)
name.pop(increment)
number.pop(increment)
del book[name2]
break
else:
print("Not available.Please try again")
while 1:
print("Contacts:")
for x in book:
print(x, ':', book[x])
print("\nWhat do you want to do?\n1.Search for a person\n2.edit the phone book\n3.exit")
choice = input()
try:
choice = int(choice)
except ValueError:
print("Type 1,2 or 3")
continue
if choice == 1:
search()
elif choice == 2:
while 1:
print("Do you want to:\n1.Add a contact\n2.Remove a contact\n3.Go back to main menu")
ch2 = input()
if ch2 in['3']:
break
else:
try:
ch2 = int(ch2)
except ValueError:
print("Type 1 or 2..")
if ch2 == 1:
add()
elif ch2 == 2:
remoe()
elif choice == 3:
exit()
else:
print("Type 1,2 or 3")
I appreciate the help.
When you choose to add a contact, it does properly add the name and number to the list. But, that is it.
When you re-run the program, the list gets re-assigned due to the first 2 lines of your code:
name = ["ranga","hari"]
number = [9895497777,9]
So, you won't see the last changes.
This is where you should maintain a file which lives outside the scope of your code, rather than a list.
You can modify your add function like this:
def add():
print("What is the name of the contact you want to add?")
name1 = input()
#name.append(name1)
# Just add the name1 variable's value to the file
with open('contacts_list.txt', 'a+') as f:
f.write(name1 + '\n')
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
#number.append(number1)
# Similarly, append the number1 variable's value to file again.
with open('contacts_list.txt', 'w+') as f:
f.write(number1)
#book[name1] = number1
with open('contacts_list.txt', 'r') as f:
print(f.read())
break
Note: You would also need to change the other functions search and remove to read and write from the file. I've just given you a taste of how things are done. You need to modify your code and make it work.
Let me know if it helps.
I took your advice and made a new text file but i still did not know how to do it but after reading ur answers i understood and at last i came to this..
removelist = []
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
def add():
print("Type the name of the contact:")
name = input()
while 1:
print("Type the number of this contact:")
number = input()
try:
number = int(number)
except ValueError:
print("Please type a number")
continue
number = str(number)
with open('output.txt', 'a+') as f:
f.write('\n' + name +' ' + number)
break
def remoe(): #this is where the problem comes in
while 1:
remove = str(input("Remove: "))
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
if not remove in["Remove", "remove"]:
removelist.clear()
data = line.find(remove)
if not data == -1:
removelist.append(line) #This saves all the lines coming from the search to a
print(removelist) #removelist which can be accessed when you type in remove
line = f.readline() #But the problem is that if there is a \n at the end of the
else: #string then the remove function does not work
line = f.readline()
else:
print(removelist)
with open('output.txt', 'r') as f:
d = f.readlines()
f.close()
with open('output.txt', 'w') as f:
for i in d:
if i not in removelist:
f.write(i)
f.truncate()
f.close()
break
while 1:
with open('output.txt', 'r') as f:
data = f.read()
print("Contacts:")
print(data)
print('''What do you want to do?
1.Search for a contact
2.Edit contacts
3.Exit''')
f.close()
choice = input()
if choice in["1"]:
search()
elif choice in["2"]:
while 1:
print('''What do you wanna do:
1.Add a contact
2.Remove a contact
3.Exit to main menu''')
ch1 = input()
if ch1 in["1"]:
add()
elif ch1 in["2"]:
remoe()
elif ch1 in["3"]:
break
else:
print("Please type 1,2 or 3")
elif choice in[3]:
print("Ok bye")
else:
print("Please type 1,2 or 3")
Now the problem seems to be the remove function..if i try to remove a line with \n at the end of it then it wont work while the opp. seems to work.Any guess what i am doing here?
And thanks for the help Mayank porwal
At the first you should know name = ["ranga","hari"], number = [9895497777,9] that you have defined are in the code and you can not change those value, and after exit() they will reset to default value.
you should use of file (for example .txt file) in this issue:
1. you must create a .txt file in your project (for example Contacts.txt)
2. and write your information in there (for example in first line: Kourosh +98938....)
3. at the first step in your program you must read Contact.txt and load it in a structure like a list or dictionary (for example
>>> with open('workfile') as f:
... read_data = f.read()
>>> f.closed
)
4.now you can edit, add, remove structure.
5.and finally you can write structure in the file, before exit()
for example:
>>> with open('workfile') as f:
... f.write(s)
>>> f.closed

Calculating the average by inputing values in a file, code produces wrong output

'''This simple program will calculate the average using files'''
num = 3
try: #set an exception in case of a file Error
while num >=0: '''read in values and place them in a file'''
value = int(input("Enter values: "))
my_file = open('my_data.txt', 'w+')
my_file.write(str(value))
numbers = my_file.readlines()
num -=1
my_file.close()
except IOError:
print('FILE FAILURE')
'''iterate to find the sum of the values in a file'''
total = 0
for ln in numbers:
total += int(ln)
'''Calculate the average'''
avg = total/len(numbers)
print("The average is %d"%(avg))#FIXME: does not calculate average
You are opening a file for write, then read from it, and assign it to a variable numbers. However this variable is not a list, although you treat it as a list when you do for ln in numbers.
Furthermore, you should end a line written to file with \n
Based on how I understand your code, you want to:
Get user input, and write it to file
From the file, read the numbers
From the numbers calculate the average
There is a statistics module, with the function mean, which will do the calculation part for you. The rest, you could (should) structure like the three bullet points above, something like this:
from statistics import mean
def inputnumbers(itterations, filename):
with open(filename, 'w') as openfile:
while itterations > 0:
try:
value=int(input("value->"))
except ValueError:
print('Numbers only please')
continue
openfile.write(str(value) + '\n')
itterations -= 1
def getaveragefromfile(filename):
numbers = []
with open(filename, 'r') as openfile:
for line in openfile.readlines():
numbers.append(int(line.replace('\n','')))
return mean(numbers)
def main():
filename = r'c:\testing\my_data.txt'
itterations = int(input('how many numbers:'))
inputnumbers(itterations, filename)
average = getaveragefromfile(filename)
print(average)
if __name__ == '__main__':
main()

Resources