race

.py

School

Yale University *

*We aren’t endorsed by this school

Course

351B

Subject

Computer Science

Date

Apr 3, 2024

Type

py

Pages

2

Uploaded by CountIron11913 on coursehero.com

''' NICK HUGHES DS2000 HW8 NOV 6TH, 2023 ''' import matplotlib.pyplot as plt # Import the custom Runner class from the 'runner' module from runner import Runner def read_data(filename): # Initialize an empty list to store Runner objects runners = [] with open(filename, 'r') as file: # Read all lines from the file into a list lines = file.readlines() # Extract the first line as the header header = lines[0] # Extract the remaining lines as data lines data_lines = lines[1:] # Iterate through the data lines for line in data_lines: # Format each line data = line.strip().split() # Extract the first value as the runner's name name = data[0] # Extract and convert numeric values as floats and remove the names runs = [float(run) for run in data[1:] if run.replace('.', '', 1).isdigit()] runner = Runner(name) # Iterate through the runs for run in runs: # Add each run to the Runner object runner.add_run(run) runners.append(runner) return runners def main(): runners = read_data('runner_data.txt') # Create a new figure for the plot plt.figure() # Iterate through the list of runners with an index for i, runner in enumerate(runners): # Different y-values for each runner runner.y = 10 * (i + 1) # Different color for each runner # Consulted https://www.geeksforgeeks.org/matplotlib-pyplot-viridis-in- python/ runner.color = plt.cm.viridis(i / len(runners)) # Iterate through days from 1 to 28 for day in range(1, 29): # Iterate through the list of runners for runner in runners: # Move each runner to the next position runner.move_next() # Draw the runner's position runner.draw()
# Add a legend to the plot plt.legend(loc="upper left") # Set the plot title and labels and x-limit plt.title("February Miles") plt.xlabel("Distance(Miles)") plt.xlim(0, 150) # Save the plot as an image with a day-specific filename # https://www.geeksforgeeks.org/matplotlib-pyplot-savefig-in-python/ plt.savefig(f"day_{day}.png") # Clear the current figure for the next day's plot # https://www.geeksforgeeks.org/matplotlib-pyplot-clf-in-python/ plt.clf() # Find the runner with the maximum distance traveled winner = max(runners, key=lambda runner: runner.x) # Print the name and distance of the winner print(f'The winner is {winner.name} with {winner.x} miles.') if __name__ == '__main__': main()
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help