Skip to content
Snippets Groups Projects
Commit 6f18a435 authored by Daniel Moix's avatar Daniel Moix
Browse files

Lecture 08

parent 4eae5b6b
Branches
No related tags found
No related merge requests found
#Program: LoopsAndFiles.py
#Purpose: Test different ways to process data from files
#Author: Adelaida Medlock
#Date: March 9, 2024
#count how many times a word appear in each line of a file
def countWordPerLine():
filename = input('Enter the name of the file to open: ')
word = input('Enter the word you want to count: ')
try :
inFile = open(filename)
lines = inFile.readlines()
inFile.close()
for index in range(len(lines)) :
count = lines[index].count(word)
print(word, 'appears', count, 'time(s) in line #', index)
except FileNotFoundError :
print('Could not find', filename)
# Read a bunch of floating-point values from a file,
# calculate some basic stats, and print results to screen
# and save the results in an output file as well
def computeStats():
# loop until we get a value filename
validFile = False
while not validFile :
try :
filename = input('Enter the name of the data file: ')
inFile = open(filename)
validFile = True
except FileNotFoundError :
print('Could not find', filename, 'Try again')
# read data from file and process it
lines = inFile.readlines()
inFile.close()
count = 0
total = 0.0
for item in lines :
count += 1
total = total + float(item)
average = total / count
# display results
print('\nStats for data in file')
print('Number of values:', count)
print('Sum of values: {:.2f}'.format(total))
print('Average of values: {:.2f}'.format(average))
# saving results to output file
outFile = open('stats.txt', 'w')
outFile.write('Stats for data in file\n')
outFile.write('Number of values: {:d}\n'.format(count))
outFile.write('Sum of values: {:.2f}\n'.format(total))
outFile.write('Average of values: {:.2f}\n'.format(average))
outFile.close()
# Calculate stats for values stored in a file
# Save results in a an output file
# Demo how to use the with statement so files
# are automatically closed
def withDemo(filename):
with open(filename, 'r') as inFile :
total = 0.0
count = 0
# Read one line at the time
line = inFile.readline()
while line != '' : # an empty string indicates the EOF
total = total + float(line)
count += 1
line = inFile.readline()
# Saving results to output file
outFile = open('stats2.txt', 'w')
outFile.write('Stats for data in file\n')
outFile.write('Number of values: {:d}\n'.format(count))
outFile.write('Sum of values: {:.2f}\n'.format(total))
outFile.write('Average of values: {:.2f}\n'.format(total / count))
# By using with both files are automatically closed
# Display results
print('\nStats for data in file')
print('Number of values:', count)
print('Sum of values: {:.2f}'.format(total))
print('Average of values: {:.2f}'.format(total / count))
print('Results have been saved to file stat2.txt')
\ No newline at end of file
#Program: QuizAverages.py
#Purpose: Calculate the average of 3 quizzes for each student in a course.
# Data for each quiz is stored in a separate text file.
# The data file is formatted as follows:
# firstName\tlastName\tuserID\tquizGrade
# For example: Harry Potter hp123 95.75
# The results will be saved in an output file. The should be
# a line for each student, in the format:
# userID\tquizAverage
#
#Author: Adelaida Medlock
#Date: March 8, 2024
'''
Purpose: This function asks the for the name of a file to be open for reading.
If the file exists and it can be open then the contents of the file are
read and returned as a list. Otherwise the user gets an error message
and is asked to try again
Parameters: a string that the contains the prompt for the user
Return Value: a list with the data from the file
Sample Call: fileData = getData('Enter the name of the data file:')
'''
def getData(prompt) :
validFile = False
while not validFile :
filename = input(prompt)
try :
inFile = open(filename, 'r')
validFile = True
except FileNotFoundError :
print('Error:', filename, 'not found. Try again.')
lines = inFile.readlines()
inFile.close()
return lines
'''
Purpose: Given student data in a list, update a dictionary to store the total of
the quiz scores for quizzes taken by each student in the list
Parameters: a list in which each element has the form: "firstName\tlastName\tuserID\tquizGrade\n"
a dictionary that to be populated with the pairs: userID : quizTotal
Return Value: none
Sample Call: accumulateScores(studentsData, scoresDictionary )
'''
def accumulateScores(dataList, runningTotal):
for line in dataList :
line = line.split('\t')
userID = line[2]
grade = line[3]
runningTotal[userID] = runningTotal.get(userID, 0) + float(grade)
# the main script
if __name__ == "__main__":
# create a dictionary to store the sum of quizzes per student
quizzesTotal = {}
# get the data from each data file and process it
quiz1_Data = getData('Enter name of file 1: ')
accumulateScores(quiz1_Data, quizzesTotal)
quiz2_Data = getData('Enter name of file 2: ')
accumulateScores(quiz2_Data, quizzesTotal)
quiz3_Data = getData('Enter name of file 3: ')
accumulateScores(quiz3_Data, quizzesTotal)
# store each student's quiz average in a second dictionary
averages = {}
for userID in quizzesTotal :
average = quizzesTotal[userID] / 3
averages[userID] = round(average, 2)
# save results to output file
outFile = open('report.txt', 'w')
for userID in averages :
outFile.write('{}\t{:.2f}\n'.format(userID, averages[userID]))
outFile.close()
# print results to screen
print('\nUser ID\tQuiz Average')
for userID in averages :
print('{}\t{:.2f}'.format(userID, averages[userID]))
print('\nResults have been save to output file')
Brenda
1000.00
1500.50
4700.00
5010.75
6629.35
3007.50
2153.44
2531.50
8507.35
8516.44
6675.60
1433.44
4963.88
6832.88
1953.35
3059.90
1860.50
4488.44
3678.00
8575.50
3548.25
2000.50
3500.75
9366.30
1098.35
1587.50
5871.60
8099.88
7925.75
2562.50
5706.44
6901.35
3033.60
6720.50
5190.75
scores = {'jb214' : 66, 'led125' : 65, 'hc357' : 70, 'kc368' : 95}
while True:
user = input("Enter userID to Lookup: ")
answer = scores.get(user, "Unknown")
print(answer)
print("Hello CS 171")
# container = ["Blue", "Yellow", "Red"]
#
# for i in range(len(container)):
# print(f"The item at position {i} is {container[i]}")
#
# for item in container:
# print(f"This item is {item}")
file = open("data.txt", "r")
# text = file.read() -- gives us all the text
# text = file.readline() -- gives us one line
list = file.readlines()
sum = 0
for lineNumber in range(len(list)):
try:
value = float(list[lineNumber])
sum = sum + value
except:
print(f"Ignoring line {lineNumber+1}")
print(f"The total is {sum}")
Earliest-known 'dead' galaxy spotted by Webb telescope
By Will Dunham
March 6, 202411:07 AM EST
WASHINGTON, March 6 (Reuters) - The James Webb Space Telescope since becoming operational in 2022 has uncovered numerous surprises about what things were like in the universe's early stages. We now can add one more - observations of a galaxy that was already "dead" when the universe was only 5% of its current age.
Scientists said on Wednesday that Webb has spotted a galaxy where star formation had already ceased by roughly 13.1 billion years ago, 700 million years after the Big Bang event that gave rise to the universe. Many dead galaxies have been detected over the years, but this is the earliest by about 500 million years.
In some ways, this galaxy is like the late Hollywood actor James Dean, famous for his "live fast, die young" life story.
"The galaxy seemed to have lived fast and intensely, and then stopped forming stars very rapidly," said astrophysicist Tobias Looser of the Kavli Institute for Cosmology at the University of Cambridge, lead author of the study published in the journal Nature, opens new tab.
"In the first few hundred million years of its history, the universe was violent and active, with plenty of gas around to fuel star formation in galaxies. That makes this discovery particularly puzzling and interesting," Looser added.
This galaxy is relatively small, with perhaps 100 million to one billion stars. That would put it in the neighborhood of the mass of the Small Magellanic Cloud dwarf galaxy situated near our Milky Way, though that one is still forming new stars.
After a galaxy stops forming new stars, it becomes a bit like a stellar graveyard.
"Once star formation ends, existing stars die and are not replaced. This happens in a hierarchical fashion, by order of stellar weight, because the most massive stars are the hottest and shine the brightest, and as a result have the shortest lives," Kavli Institute astrophysicist and study co-author Francesco D'Eugenio said.
"As the hottest stars die, the galaxy color changes from blue - the color of hot stars - to yellow to red - the color of the least massive stars," D'Eugenio added. "Stars about the mass of the sun live about 10 billion years. If this galaxy stopped forming stars at the time we observed it, there would be no sun-like stars left in it today. However, stars much less massive than the sun can live for trillions of years, so they would continue to shine long after star formation stopped."
The researchers determined that this galaxy experienced a burst of star formation spanning 30 to 90 million years, then it suddenly stopped. They are trying to figure out why.
It could be, they said, due to the action of a supermassive black hole at the galactic center or a phenomenon called "feedback" - blasts of energy from newly formed stars - that pushed the gas needed to form new stars out of the galaxy.
"Alternatively, gas can be consumed very quickly by star formation, without being promptly replenished by fresh gas from the surroundings of the galaxy, resulting in galaxy starvation," Looser said.
NASA's Webb is able to look at greater distances, and thus farther back in time, than its Hubble Space Telescope predecessor. Among other discoveries, Webb has enabled astronomers to see the earliest-known galaxies, which have turned out to be larger and more plentiful than expected.
In the new study, the researchers were able to observe the dead galaxy at one moment in time. It is possible, they said, that it later resumed star formation.
"Some galaxies may undergo rejuvenation, if they can find fresh gas to convert into new stars," D'Eugenio said. "We do not know the ultimate fate of this galaxy. This may depend on what mechanism caused star formation to stop."
\ No newline at end of file
age = None
while age is None:
try:
# Code that could fail
age = int(input("Enter your age: "))
except:
# What to do in case of failure
print("Oops. Try again")
print(f"Next year you will be {age + 1}")
\ No newline at end of file
ka123 83.67
ha146 87.00
ra158 93.67
ca170 88.00
bfb234 65.00
gb246 87.00
hmb257 79.50
inb268 88.67
job279 85.00
db280 83.00
edb291 80.67
jb214 80.67
led125 82.00
hc357 80.67
kc368 91.00
sc379 87.67
fac380 84.33
jdc391 82.00
abc302 89.33
brc313 73.00
aed468 81.50
jd479 88.00
cbd479 94.00
ed480 84.00
fd491 87.00
mwd402 88.00
bda413 84.00
idc424 88.00
jdl435 90.00
ldl457 95.50
Karen Abbott ka123 85
Henry Abraham ha146 77
Robert Abrahams ra158 100
Cornelia Adair ca170 95
Benjamin Bache bfb234 47
Gamaliel Bailey gb246 78
Henry Baird hmb257 64
Newton Baker inb268 88
John Balderston job279 80
Dirk Ballendorf db280 79
Digby Baltzell edb291 76
Josiah Bancroft jb214 66
Leslie Banks led125 65
Henry Cadbury hc357 70
Kacen Callender kc368 95
Stephanie Camp sc379 89
Francesca Canfield fac380 74
John Carr jdc391 75
Beverly Carter abc302 87
Barrie Cassileth brc313 51
\ No newline at end of file
Karen Abbott ka123 90
Henry Abraham ha146 89
Robert Abrahams ra158 85
Cornelia Adair ca170 84
Benjamin Bache bfb234 83
Gamaliel Bailey gb246 96
Henry Baird hmb257 95
Newton Baker inb268 91
John Balderston job279 83
Dirk Ballendorf db280 87
Digby Baltzell edb291 87
Josiah Bancroft jb214 89
Leslie Banks led125 87
Henry Cadbury hc357 91
Kacen Callender kc368 81
Stephanie Camp sc379 98
Francesca Canfield fac380 88
John Carr jdc391 85
Beverly Carter abc302 91
Barrie Cassileth brc313 87
Alice Dark aed468 88
Joie Davidow jd479 88
Charles Davis cbd479 94
Emilie Davis ed480 84
Francis Davis fd491 85
Marianna Davis mwd402 88
Barbara Angelis bda413 84
Benjamin Casseres idc424 88
John Lancie jdl435 89
Louis Lange ldl457 100
\ No newline at end of file
Karen Abbott ka123 76
Henry Abraham ha146 95
Robert Abrahams ra158 96
Cornelia Adair ca170 85
Newton Baker inb268 87
John Balderston job279 92
Dirk Ballendorf db280 83
Digby Baltzell edb291 79
Josiah Bancroft jb214 87
Leslie Banks led125 94
Henry Cadbury hc357 81
Kacen Callender kc368 97
Stephanie Camp sc379 76
Francesca Canfield fac380 91
John Carr jdc391 86
Beverly Carter abc302 90
Barrie Cassileth brc313 81
Alice Dark aed468 75
Francis Davis fd491 89
Marianna Davis mwd402 88
Barbara Angelis bda413 84
Benjamin Casseres idc424 88
John Lancie jdl435 91
Louis Lange ldl457 91
def loadScores(filename, scores):
try:
file = open(filename, "r")
for line in file.readlines():
parts = line.split("\t")
username = parts[2]
score = float(parts[3])
if username in scores:
theirScores = scores[username]
theirScores.append(score)
else:
scores[username] = [score]
file.close()
except:
print(f"Error importing {filename}. Skipping.")
def saveAverages(filename, scores):
try:
file = open(filename, "w") # This erases filename
for userid in scores:
studentScores = scores[userid]
average = sum(studentScores) / len(studentScores)
file.write(f"{userid}\t{average:.02f}\n")
file.close()
except Exception as e:
print(f"Could not write to {filename}. Oops.")
print(f"The exception said {e}")
# Read first file
scores = {}
loadScores("quiz1.txt", scores)
loadScores("quiz2.txt", scores)
loadScores("quiz3.txt", scores)
saveAverages("out.txt", scores)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment