每周挑战:平均进度
发布: (2025年12月14日 GMT+8 19:58)
3 min read
原文: Dev.to
Source: Dev.to
Weekly Challenge 351
每周 Mohammad S. Anwar 会发布 The Weekly Challenge,为我们提供两个每周任务的解答机会。我的解答先用 Python 编写,然后转换为 Perl。这是我们练习编码的好方式。
Task 1: Special Average
Task
给定一个整数数组。编写脚本返回该数组在去除最小值和最大值后的平均值。
My solution (Python)
def special_average(ints: list) -> float:
min_value = min(ints)
max_value = max(ints)
short_list = [n for n in ints if n != min_value and n != max_value]
if not short_list:
return 0
return sum(short_list) / len(short_list)
My solution (Perl)
sub main (@ints) {
my $min_value = min(@ints);
my $max_value = max(@ints);
my @short_array = grep { $_ != $min_value && $_ != $max_value } @ints;
if ($#short_array == -1) {
say 0;
}
say sum(@short_array) / scalar(@short_array);
}
Examples
$ ./ch-1.py 8000 5000 6000 2000 3000 7000
5250.0
$ ./ch-1.py 100000 80000 110000 90000
95000.0
$ ./ch-1.py 2500 2500 2500 2500
0
$ ./ch-1.py 2000
0
$ ./ch-1.py 1000 2000 3000 4000 5000 6000
3500.0
Task 2: Arithmetic Progression
Task
给定一个数字数组。编写脚本,如果该数组可以重新排列成等差数列则返回 true,否则返回 false。
如果任意两个相邻元素的差值相同,则该数列称为等差数列。
My solution (Python)
浮点数精度可能会出现问题(例如 0.1 + 0.2 != 0.3)。为获得可靠结果,输入应为整数或 Decimal 类型。
def arithmetic_progression(ints: list) -> bool:
sorted_ints = sorted(ints)
diff = sorted_ints[1] - sorted_ints[0]
for i in range(2, len(sorted_ints)):
if sorted_ints[i] - sorted_ints[i - 1] != diff:
return False
return True
My solution (Perl)
Perl 也会遇到相同的浮点数问题;可以使用 Math::BigFloat 提高精度。
sub main (@ints) {
my @sorted_ints = map { Math::BigFloat->new($_) } sort { $a $b } @ints;
my $diff = $sorted_ints[1] - $sorted_ints[0];
foreach my $i ( 2 .. $#sorted_ints ) {
if ( $sorted_ints[$i] - $sorted_ints[ $i - 1 ] != $diff ) {
say 'false';
return;
}
}
say 'true';
}
Examples
$ ./ch-2.py 1 3 5 7 9
True
$ ./ch-2.py 9 1 7 5 3
True
$ ./ch-2.py 1 2 4 8 16
False
$ ./ch-2.py 5 -1 3 1 -3
True
$ ./ch-2.py 1.5 3 0 4.5 6
True
$ ./ch-2.py 0.1 0.3 0.2 0.4
True