NVIDIA Interview Question

Read in an input string simulating a csv upload of cities and temperatures and return the average temp

Interview Answer

Anonymous

Jul 11, 2024

def parse_cities_and_temperatures(string): # Split the input string by newlines to get each city-temperature pair lines = string.strip().split('\n') # Initialize an empty list to store the parsed data cities_and_temperatures = [] # Iterate over each line for line in lines: # Split each line by the comma to separate the city and temperature city, temperature = line.split(',') # Strip whitespace and convert temperature to float, then store as a tuple cities_and_temperatures.append((city.strip(), float(temperature.strip()))) return cities_and_temperatures # Example usage csv_string = """New York, 20.5 Los Angeles, 25.3 Chicago, 15.2 Houston, 30.0 Phoenix, 33.5""" parsed_data = parse_cities_and_temperatures(csv_string) for city, temperature in parsed_data: print(f"City: {city}, Temperature: {temperature}")