# 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} ... }
defto_dict_load(data):all_towns=data.split("\n")town_wise={}foriinrange(len(all_towns)):town_name,values=all_towns[i].split(":")values=values.split(",")vals=[float(v.split(" ")[1])forvinvalues]mean=sum(vals)/len(vals)variance=sum(map(lambdax:(x-mean)*(x-mean),vals))/len(vals)town_wise[town_name]={'mean':mean,'variance':variance}returntown_wise# returns mean of rainfall in a town according to data
defmean(town,data):dt=to_dict_load(data)iftownindt:returndt[town]['mean']return-1# returns variance of rainfall in a town according to data
defvariance(town,data):dt=to_dict_load(data)iftownindt:returndt[town]['variance']return-1
constparseData=(string)=>{// Return map of cities and their rainfalls, assumes well-formed datareturnstring.split('\n').map(line=>line.split(':')).map(cityMonths=>{return{city:cityMonths[0],rainfalls:cityMonths[1].split(',').map(month=>parseFloat(month.split('')[1])).filter(r=>!isNaN(r))}}).reduce((m,cityRainfalls)=>{m[cityRainfalls.city]=cityRainfalls.rainfallsreturnm},{})}constcalcMean=(nums)=>nums.reduce((t,n)=>t+n,0)/nums.lengthconstcalcVariance=(nums)=>{constmean=calcMean(nums)returncalcMean(nums.map(num=>Math.pow(num-mean,2)))}constmean=(town,string)=>{constcityRainfallsMap=parseData(string)if(!cityRainfallsMap[town]||cityRainfallsMap[town].length<1)return-1returncalcMean(cityRainfallsMap[town])}constvariance=(town,string)=>{constcityRainfallsMap=parseData(string)if(!cityRainfallsMap[town]||cityRainfallsMap[town].length<1)return-1returncalcVariance(cityRainfallsMap[town])}// Tests assume data, data1 in scopeconsttest=(fn,town,string,expected)=>{constresult=fn(town,string)console.log(`${town}${result} === ${expected} ?`)}test(variance,"London",data,57.42833333333374)test(mean,"London",data,51.199999999999996)test(mean,"Seattle",data,-1)test(variance,"Seattle",data,-1)test(mean,"Seattle","Seattle:",-1)test(variance,"Seattle","Seattle:",-1)test(variance,'Beijing',data1,'4437.0380555556')test(variance,'Lima',data,'1.5790972222222')
Javascript with regex
Fyi, you can add language specific syntax styling immediately after the first code back-ticks.
github.com/adam-p/markdown-here/wi...
Ah! I hadn't closed the three back ticks!
Thanks, Matt. I tried that, and if you see my other posts you'll see I was successful, but it's not working for this one for some reason
Python solution
Solution in Haskell:
JS solution
JS Solution
output:
TypeScript
My Swift solution, not the best ☹️: