My Swift solution, not the best ☹️:
func fetchCity(datas: String) -> [String: [Double]] { func fetchCityDatas(datas: String) -> [Double] { datas.split(separator: ",").map { Double($0.split(separator: .init(" ")).last ?? "") ?? 0 } } return data.split(separator: "\n").reduce(into: [String:[Double]]()) { let data = $1.split(separator: ":") $0[String(data.first ?? "")] = fetchCityDatas(datas: String(data.last ?? "")) } } func mean(town: String, datas: String) -> Double { let convertedDatas = fetchCity(datas: datas) guard convertedDatas.contains(where: { $0.key == town }), let townDatas = convertedDatas[town] else { return -1 } let sum = townDatas.reduce(into: 0.0) { $0 += $1 } return sum / Double(townDatas.count) } func variance(town: String, datas: String) -> Double { let meanValue = mean(town: town, datas: datas) let convertedCities = fetchCity(datas: datas) guard let convertedDatas = convertedCities[town] else { return 0 } return convertedDatas.map { pow((meanValue - $0),2) } .reduce(into: 0.0) { $0 += $1 } / Double(convertedDatas.count) } mean(town: "Rome",datas: data1) mean(town: "Beijing",datas: data) variance(town: "Beijing",datas: data1) variance(town: "Lima",datas: data)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
My Swift solution, not the best ☹️: