Inspired by this question.
Given a list containing numbers, print:
- The sum and product of the numbers in the list
- The average and median
- The differences between each term in the list (e.g.
[1,2,3] -> [1,1]: 1+1=2, 2+1=3) - The list, sorted ascending
- The minimum and maximum of the list
- The standard deviation of the list
For reference:
Standard Deviation
$$\sigma=\sqrt{\frac1N\sum^N_{i=1}(x_i-\mu)^2}$$
Where \$\mu\$ is the mean average, \$x_i\$ is the \$i\$th term in the list, and \$N\$ is the length of the list.
Shortest code wins. Good luck!
-
2\$\begingroup\$ Do we have to print them in that order? \$\endgroup\$Titus– Titus2018年10月02日 15:15:00 +00:00Commented Oct 2, 2018 at 15:15
17 Answers 17
Q, 41
{(+/;*/;avg;med;-':;asc;min;max;dev)@\:x}
TI-BASIC, 41 bytes
1-Var Stats is one byte, and Σx, x̄, etc. are two bytes each.
Ans→L1
1-Var Stats
SortA(L1
Disp Σx,prod(Ans),x̄,Med,ΔList(Ans),L1,minX,maxX,σx
If changing the output order is allowed, a close-paren can be saved, bringing the score to 40 bytes.
J, (削除) 73 (削除ここまで) 70 characters
((+/;*/;a;(<.@-:@#{/:~);2&-~/\;/:~;<./;>./;%:@:(a@:*:@:(-a)))[a=.+/%#)
Usage:
((+/;*/;a;(<.@-:@#{/:~);2&-~/\;/:~;<./;>./;%:@:(a@:*:@:(-a)))[a=.+/%#)1 2 3 4
+--+--+---+-+-------+-------+-+-+-------+
|10|24|2.5|3|1 1 1 1|1 2 3 4|1|4|1.11803|
+--+--+---+-+-------+-------+-+-+-------+
-
\$\begingroup\$ It has to be 1 1 1 not 1 1 1 1 as difference itself next \$\endgroup\$user58988– user589882018年01月06日 10:37:13 +00:00Commented Jan 6, 2018 at 10:37
Q (87 chars)
(sum;prd;avg;{.5*(sum/)x[((<)x)(neg(_)t;(_)neg t:.5*1-(#)x)]};(-':);asc;min;max;dev)@\:
eg.
q) (sum;prd;avg;{.5*(sum/)x[((<)x)(neg(_)t;(_)neg t:.5*1-(#)x)]};(-':);asc;min;max;dev)@\: 10 9 8 7 6 5 4 3 2 1
55
3628800
5.5
5.5
10 -1 -1 -1 -1 -1 -1 -1 -1 -1
`s#1 2 3 4 5 6 7 8 9 10
1
10
2.872281
Ruby 187
O=->l{g=l.size
r=l.sort
s=l.inject(:+)+0.0
m=s/g
p s,l.inject(:*),m,g%2>0?r[g/2]:(r[g/2]+r[g/2-1])/2.0,l.each_cons(2).map{|l|l[1]-l[0]},r,r[0],r[-1],(l.inject(0){|e,i|e+(i-m)**2}/g)**0.5}
Usage syntax: O[<array>] (for example, O[[1,2,3]])
Outputs all the required values to the console, in the order specified in the question.
IdeOne examples:
- with odd number of elements: http://ideone.com/83ouj
- with even number of elements: http://ideone.com/7PTRq
Julia 0.6, 66 bytes
x->map(f->f(x),[sum,prod,mean,median,diff,sort,extrema,std])|>show
Julia 0.6, 88 bytes (uncorrected std dev, as in op)
x->map(f->f(x),[sum,prod,mean,median,diff,sort,extrema,x->std(x,corrected=false)])|>show
-
\$\begingroup\$ this isn't right, because Julia is using the sample standard deviation calculation (dividing by
n-1) rather than the population std (dividing byn) as required in the problem. Multiplying by(n-1)/nwouldn't fix it either, because when dividing byn-1,NaNis produced. I ran into the same problems when trying to do this in R and haven't given it thought since. \$\endgroup\$Giuseppe– Giuseppe2018年01月05日 17:30:34 +00:00Commented Jan 5, 2018 at 17:30 -
\$\begingroup\$ That didn't even occur to me. I added an alternate solution with the correct std deviation. \$\endgroup\$gggg– gggg2018年01月05日 20:35:40 +00:00Commented Jan 5, 2018 at 20:35
-
Scala (削除) 208 (削除ここまで) (削除) 202 (削除ここまで) 188:
val w=l.size
val a=l.sum/w
val s=l.sortWith(_<_)
Seq(l.sum,l.product,a,s((w+1)/2),(0 to w-2).map(i=>l(i+1)-l(i)),s,l.min,l.max,(math.sqrt((l.map(x=>(a-x)*(a-x))).sum*1.0/w))).map(println)
Test:
scala> val l = util.Random.shuffle((1 to 6).map(p=>math.pow(2, p).toInt))
l: scala.collection.immutable.IndexedSeq[Int] = Vector(64, 8, 4, 32, 16, 2)
scala> val a=l.sum/l.size
a: Int = 21
scala> val s=l.sortWith(_<_)
s: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 8, 16, 32, 64)
scala> Seq(l.sum,l.product,a,s((s.size+1)/2),(0 to l.size-2).map(i=>l(i+1)-l(i)),l.sortWith(_<_),l.min,l.max,(math.sqrt((l.map(x=>(a-x)*(a-x))).sum*1.0/l.size))).map(println)
126
2097152
21
16
Vector(-56, -4, 28, -16, -14)
Vector(2, 4, 8, 16, 32, 64)
2
64
21.656407827707714
-
\$\begingroup\$ For me "Vector(-56, -4, 28, -16, -14)" is wrong \$\endgroup\$user58988– user589882018年01月06日 10:38:06 +00:00Commented Jan 6, 2018 at 10:38
-
\$\begingroup\$ @RosLuP: Why is it wrong? \$\endgroup\$user unknown– user unknown2018年01月07日 00:31:29 +00:00Commented Jan 7, 2018 at 0:31
-
\$\begingroup\$ Yes you are right if input is "Vector(64, 8, 4, 32, 16, 2)" ( i confuse the input) \$\endgroup\$user58988– user589882018年01月07日 12:50:05 +00:00Commented Jan 7, 2018 at 12:50
Jelly, 27 bytes
_ÆmÆḊ÷L1⁄2$
Wẋ9SPÆmÆṁIṢṂṀÇ9ƭ€
How it works
_ÆmÆḊ÷L1⁄2$ - Helper link. Takes a list l on the left
Æm - Yield the mean of l
_ - Subtract the mean from each element of l
ÆḊ - Calculate the norm
$ - Run the previous two commands over l:
L - Length of l
1⁄2 - Square root
÷ - Divide the norm by the square root of l's length
Wẋ9SPÆmÆṁIṢṂṀÇ9ƭ€ - Main link. Takes a list l on the left
W - Yield [l]
ẋ9 - Repeat 9 times
9ƭ€ - Generate a 9 element list by running the previous 9 commands over l
and collecting the results together:
S - Sum
P - Product
Æm - Mean
Æṁ - Median
I - Forward increments
Ṣ - Sort
Ṃ - Minimum
Ṁ - Maximum
Ç - Helper link (standard deviation)
Factor + math.unicode, 90 bytes
[| s | s Σ s Π s mean s median s differences s [ > ] sort s minmax s population-std .s ]
Should be pretty self-explanatory, I hope. Factor has a built-in for each of these, but only a few have short aliases. While cleaving is cool, it's much shorter to go with locals here. Locals are also shorter than storing the words in a list and using [ execute ] with each on them, which would eventually catch up if the list had been re-used even more.
Python 3.8, (削除) 174 (削除ここまで) (削除) 167 (削除ここまで) (削除) 148 (削除ここまで) 147 bytes
-7 bytes thanks to @wasif
-19 bytes thanks to math.prod()
-1 bytes thanks to @The Fifth Marshal
lambda l:[sum(l),math.prod(l),mean(l),median(l),[m-n for n,m in zip(l,l[1:])],sorted(l),min(l),max(l),stdev(l)]
import math
from statistics import*
-
\$\begingroup\$ The code didn't work. Did you test it? Python doesn't have prod() and your forward differences calculation was wrong. I fixed it for you with 7 bytes saved \$\endgroup\$avarice– avarice2021年09月23日 16:35:15 +00:00Commented Sep 23, 2021 at 16:35
-
\$\begingroup\$ In PyCharm, math.prod works in Python 3.8. Maybe it is 3.8+ specific? \$\endgroup\$Alan Bagel– Alan Bagel2021年09月23日 16:42:09 +00:00Commented Sep 23, 2021 at 16:42
-
\$\begingroup\$ yes maybe. If that's the case you should add "3.8" to language name. But please also fix the forward differences calculation \$\endgroup\$avarice– avarice2021年09月23日 16:43:50 +00:00Commented Sep 23, 2021 at 16:43
-
\$\begingroup\$
math.prodindeed has been added in Python 3.8, so you might want to edit it back in again: docs.python.org/3.8/library/math.html#math.prod BTW: the post does not match the tio linked code \$\endgroup\$movatica– movatica2021年09月27日 13:10:03 +00:00Commented Sep 27, 2021 at 13:10 -
\$\begingroup\$ -1 byte \$\endgroup\$The Fifth Marshal– The Fifth Marshal2021年10月04日 18:32:56 +00:00Commented Oct 4, 2021 at 18:32
C++14, (削除) 340 (削除ここまで) 383 bytes
As generic unnamed lambda. First parameter L is the list as std::list of floating point type and second parameter is the desired output stream, like std::cout.
#import<cmath>
#define F(x);O<<x<<'\n';
#define Y l=k;++l!=L.end();
#define A auto
[](A L,A&O){A S=L;A l=L.begin(),k=l;A n=L.size();A s=*l,p=s,d=s*s,h=n/2.;for(S.sort(),Y s+=*l,p*=*l,d+=*l**l);for(l=S.begin();--h>0;++l)F(s)F(p)F(s/n)F(*l)for(Y)O<<*l-*k++<<","F(' ')for(A x:S)O<<x<<","F(' ')F(S.front())F(S.back())F(sqrt((d-s*s/n)/(n-1)))}
Compiles with a warning, C++ does not allow " directly followed by literals like F. Program still running.
- -1 & -2 bytes thanks to Zacharý
Ungolfed:
#include<iostream>
#include<list>
#import<cmath>
#define F(x);O<<x<<'\n';
#define Y l=k;++l!=L.end();
#define A auto
auto f=
[](A L, A&O){
A S=L; //copy the list for later sorting
A l=L.begin(), //main iterator
k=l; //sidekick iterator
A n=L.size();
A s=*l, //sum, init with head of list
p=s, //product, same
d=s*s, //standard deviation, formula see https://en.wikipedia.org/wiki/Algebraic_formula_for_the_variance
h=n/2.; //for the median later
for(
S.sort(), //now min/med/max is at known positions in S
Y //l=k;++l!=L.end(); //skip the headitem-loop
s += *l, //l points the next element which is fine
p *= *l, //since the head given at definiten
d += *l * *l //needs the sum of the squares
);
for(
l=S.begin(); //std::list has no random access
--h>0; //that's why single increment loop
++l //until median is crossed
)
F(s) //;O<<s<<'\n'; //sum
F(p) //product
F(s/n) //average
F(*l) //median (in S)
for(Y) //l=k;++l!=L.end(); //set l back to L
O<<*l-*k++<<"," //calc difference on the fly
F(' ')
for(A x:S) //output sorted list
O<<x<<","
F(' ')
F(S.front()) //minimum
F(S.back()) //maximum
F(sqrt((d-s*s/n)/(n-1))) //standard deviation
}
;
using namespace std;
int main() {
list<double> l = {10,3,1,2,4};
f(l, cout);
}
-
\$\begingroup\$ I think you can save a few bytes by changing
Fto;F(x)O<<x<<'\n';and the last line to:[](A L,A&O){A S=L;A l=L.begin(),k=l;A n=L.size();A s=*l,p=s,d=s*s,h=n/2.;for(S.sort(),Y s+=*l,p*=*l,d+=*l**l);for(l=S.begin();--h>0;++l)F(s)F(p)F(s/n)F(*l)for(Y)O<<*l-*k++<<","F(' ')for(A x:S)O<<x<<","F(' ')F(S.front())F(S.back())F(sqrt((d-s*s/n)/(n-1)));}\$\endgroup\$Adalynn– Adalynn2017年08月11日 22:38:52 +00:00Commented Aug 11, 2017 at 22:38 -
\$\begingroup\$ @Zacharý There was indeed an unnecessary
;quite at the end. That could be removed, but the compiler does not like" "F:warning: invalid suffix on literal; C++11 requires a space between literal and string macroit compiles though... \$\endgroup\$Karl Napf– Karl Napf2017年08月11日 22:48:27 +00:00Commented Aug 11, 2017 at 22:48 -
\$\begingroup\$ Does it work though?! \$\endgroup\$Adalynn– Adalynn2017年08月11日 22:54:14 +00:00Commented Aug 11, 2017 at 22:54
-
\$\begingroup\$ @Zacharý yes it does work. \$\endgroup\$Karl Napf– Karl Napf2017年08月11日 23:01:52 +00:00Commented Aug 11, 2017 at 23:01
-
\$\begingroup\$ 327 bytes \$\endgroup\$ceilingcat– ceilingcat2019年03月17日 23:13:26 +00:00Commented Mar 17, 2019 at 23:13
Perl 5, 204 + 1 = 205 bytes
@L=sort{$a<=>$b}@F;$p=1;$s+=$_,$p*=$_,$a+=$_/@F for@L;for(0..$#F){$o=($F[$_]-$a)**2/@F;push@d,$F[$_]-$F[$_-1]if$_}$o=sqrt$o;$m=@F%2?$F[@F/2]:$F[@F/2]/2+$F[@F/2-1]/2;say"$s $p$/$a $m$/@d$/@L$/@L[0,-1]$/$o"
Pyt, 39 bytes
←ĐĐĐĐĐĐĐŞ⇹Ʃ3ȘΠ4Șμ5Ș−⇹6Ș↕⇹7ȘṀ↔ĐĐμ-2Ʃ⇹Ł/√
This outputs, in order, the median, the product, the differences, the list reversed, the sum, the maximum and minimum, the mean, and the standard deviation.q
Explanation:
←ĐĐĐĐĐĐĐ Push the array onto the stack 8 times
ş Sort in ascending order
⇹ Stack management
Ʃ Sum
3Ș Stack management
Π Product
4Ș Stack management
μ Mean (as a float)
5Ș Stack management
− Differences
⇹6Ș Stack management
↕ Minimum and maximum
⇹7Ș Stack management
Ṁ Median
↔ Stack management
ĐĐμ-2Ʃ⇹Ł/√ Standard Deviation
APL NARS, 119 chars, 182 bytes
{m←(s←+/w)÷n←⍴w←,⍵⋄s,(×ばつ/w),m,(n{j←⌊⍺÷2⋄2|⍺:⍵[1+j]⋄2÷⍨⍵[j]+⍵[j+1]}t),(⊂ ̄1↓(1⌽w)-w),(⊂t←w[⍋w]),(⌊/w),(⌈/w),√n÷⍨+/(w-m)*2}
test
h←{m←(s←+/w)÷n←⍴w←,⍵⋄s,(×ばつ/w),m,(n{j←⌊⍺÷2⋄2|⍺:⍵[1+j]⋄2÷⍨⍵[j]+⍵[j+1]}t),(⊂ ̄1↓(1⌽w)-w),(⊂t←w[⍋w]),(⌊/w),(⌈/w),√n÷⍨+/(w-m)*2}
⎕fmt h 0
┌9──────────────────────┐
│ ┌0─┐ ┌1─┐ │
│0 0 0 0 │ 0│ │ 0│ 0 0 0│
│~ ~ ~ ~ └~─┘ └~─┘ ~ ~ ~2
└∊──────────────────────┘
⎕fmt h 3
┌9──────────────────────┐
│ ┌0─┐ ┌1─┐ │
│3 3 3 3 │ 0│ │ 3│ 3 3 0│
│~ ~ ~ ~ └~─┘ └~─┘ ~ ~ ~2
└∊──────────────────────┘
⎕fmt h 1 2 3
┌9───────────────────────────────────────┐
│ ┌2───┐ ┌3─────┐ │
│6 6 2 2 │ 1 1│ │ 1 2 3│ 1 3 0.8164965809│
│~ ~ ~ ~ └~───┘ └~─────┘ ~ ~ ~~~~~~~~~~~~2
└∊───────────────────────────────────────┘
⎕fmt h 1 2 3 4
┌9────────────────────────────────────────────────┐
│ ┌3─────┐ ┌4───────┐ │
│10 24 2.5 2.5 │ 1 1 1│ │ 1 2 3 4│ 1 4 1.118033989│
│~~ ~~ ~~~ ~~~ └~─────┘ └~───────┘ ~ ~ ~~~~~~~~~~~2
└∊────────────────────────────────────────────────┘
⎕fmt h 1 2 7 3 4 5
┌9──────────────────────────────────────────────────────────────────┐
│ ┌5──────────┐ ┌6───────────┐ │
│22 840 3.666666667 3.5 │ 1 5 ̄4 1 1│ │ 1 2 3 4 5 7│ 1 7 1.972026594│
│~~ ~~~ ~~~~~~~~~~~ ~~~ └~──────────┘ └~───────────┘ ~ ~ ~~~~~~~~~~~2
└∊──────────────────────────────────────────────────────────────────┘
Ocaml - 288 bytes
Assuming the given list is a non-empty list of floats (to avoid conversions), and that the returned median is the weak definition of the median :
median l = nsuch that half the elements oflare smaller or equal tonand half the elements oflare greater or equal ton
open List
let f=fold_left
let z=length
let s l=f(+.)0. l
let a l=(s l)/.(float_of_int(z l))let rec i=function|a::[]->[]|a::b->(hd b -. a)::(i b)let r l=let t=sort compare l in(s,f( *.)1. l,a t,nth t((z t)/2+(z t)mod 2-1),t,i l,nth t 0,nth t((z t)-1),sqrt(a(map(fun n->(n-.(a l))**2.)l)))
The readable version is
open List
let sum l = fold_left (+.) 0. l
let prod l = fold_left ( *. ) 1. l
let avg l = (sum l) /. (float_of_int (length l))
let med l =
let center = (length l) / 2 + (length l) mod 2 -1 in
nth l center
let max l = nth l 0
let min l = nth l ((length l) - 1)
let dev l =
let mean = avg l in
sqrt (avg (map (fun n -> (n -. mean)**2.) l))
let rec dif =
function
| a::[] -> []
| a::b -> ((hd b) - a) :: (dif b)
let result l =
let sorted = sort compare l in
(
sum sorted,
prod sorted,
avg sorted,
med sorted,
sorted,
dif l,
max sorted,
min sorted,
dev sorted
)
PHP, 213 bytes
function($a){echo$s=array_sum($a),_,array_product($a),_,$v=$s/$c=count($a);foreach($a as$i=>$x){$d+=($x-$v)**2;$i&&$f[]=$x-$a[$i-1];}sort($a);var_dump(($a[$c/2]+$a[$c/2+~$c%2])/2,$f,$a,$a[0],max($a),sqrt($d/$c));}
05AB1E, 27 (or 25?) bytes
If the order is mandatory:
O,P,ÅA,Åm,,円{R,ß,à,ÅA-nÅAt,
If the order doesn't matter:
O,P,Åm,,円{R,ß,à,ÅA=-nÅAt,
Does the average just before the standard deviation, every other operation is in the same order.
Explanation:
O # Sum the (implicit) input-list
, # Pop and print it with trailing newline
P, # Same for the product
ÅA, # Same for the average
Åm, # Same for the median
,円 # Same for the deltas / forward differences
{R, # Same for the descending sort (sort + reverse)
ß, # Same for the minimum
à, # Same for the maximum
# Same for the standard deviation:
ÅA # Get the average of the (implicit) input-list
- # Subtract it from each value in the (implicit) input-list
n # Square each
ÅA # Take the average of this list
t # Take the square-root of that
, # And print it as well