dataand data1 are two strings with rainfall records of a few cities for months from January to December. The records of towns are separated by \n. The name of each town is followed by :.
data and towns can be seen in “Your Test Cases:”.
Task:
function: mean(town, strng) should return the average of rainfall for the city town and the strng data or data1.
function: variance(town, strng) should return the variance of rainfall for the city town and the strng data or data1.
Examples:
mean(“London”, data), 51.19(9999999999996)
variance(“London”, data), 57.42(833333333374)
Notes:
if functions mean or variance have as parameter town a city which has no records return -1
Don’t truncate or round: the tests will pass if abs(your_result - test_result) <= 1e-2 or abs((your_result - test_result) / test_result) <= 1e-6 depending on the language (see function assertFuzzyEquals).
http://www.mathsisfun.com/data/standard-deviation.html
data and data1 are adapted from http://www.worldclimate.com
注意:城主名字的大小写
import static java.util.stream.Collectors.averagingDouble;
import java.util.ArrayList;
import java.util.List;
public class Rainfall {
public static double mean(String town, String strng) {
return parseTemp(town, strng).stream()
.collect(averagingDouble(n -> n));
}
public static double variance(String town, String strng) {
double mean = mean(town, strng);
if (mean == -1.0) return -1.0;
return parseTemp(town, strng).stream()
.collect(averagingDouble(n -> (n - mean) * (n - mean)));
}
private static List<Double> parseTemp(String town, String strng) {
List<Double> temps = new ArrayList<>();
for (String line : strng.split("\\n")) {
String[] data = line.split(":");
if (town.equals(data[0])) {
for (String weather : data[1].split(",")) {
String[] temp = weather.split("\\s");
temps.add(Double.parseDouble(temp[1]));
}
break;
}
}
if (temps.isEmpty()) temps.add(-1.0);
return temps;
}
}
本文介绍了一个用于分析城市月降雨量记录的方法,包括计算平均降雨量及降雨量的方差。通过提供的函数,可以针对特定城市的降雨数据进行统计分析。
158

被折叠的 条评论
为什么被折叠?



