DEV Community

Discussion on: Daily Challenge #216 - Rainfall

Collapse
 
vidit1999 profile image
Vidit Sarkar

Python solution

# load the data in a dictionary
# dict keys are towns
# and value is another dict with keys 'mean' and 'variancne'
# and values with mean and variance of the respective towns
# Example:
# to_dict_load(data) ->
# {'Rome': {'mean': 66.02499999999999, 'variance': 915.3852083333335},
# 'London': {'mean': 51.199999999999996, 'variance': 57.428333333333335} ... }
def to_dict_load(data):
    all_towns = data.split("\n")
    town_wise = {}
    for i in range(len(all_towns)):
        town_name, values = all_towns[i].split(":")
        values = values.split(",")
        vals = [float(v.split(" ")[1]) for v in values]
        mean = sum(vals)/len(vals)
        variance= sum(map(lambda x : (x-mean)*(x-mean), vals))/len(vals)
        town_wise[town_name] = {'mean': mean, 'variance': variance}
    return town_wise

# returns mean of rainfall in a town according to data
def mean(town, data):
    dt = to_dict_load(data)
    if town in dt:
        return dt[town]['mean']
    return -1

# returns variance of rainfall in a town according to data
def variance(town, data):
    dt = to_dict_load(data)
    if town in dt:
        return dt[town]['variance']
    return -1