# Operations with Lists

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!

• Do we have to print them in that order? Oct 2, 2018 at 15:15

# Q, 41

{(+/;*/;avg;med;-':;asc;min;max;dev)@\:x}
• 'med'...facepalm Jun 8, 2012 at 11:14
• I was wondering what you were up to! Jun 8, 2012 at 12:04

# TI-BASIC, 41 bytes

1-Var Stats is one byte, and Σx, , etc. are two bytes each.

Ans→L₁
1-Var Stats
SortA(L₁
Disp Σx,prod(Ans),x̄,Med,ΔList(Ans),L₁,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|
+--+--+---+-+-------+-------+-+-+-------+
• It has to be 1 1 1 not 1 1 1 1 as difference itself next
– user58988
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:

# Julia 0.6, 66 bytes

x->map(f->f(x),[sum,prod,mean,median,diff,sort,extrema,std])|>show

Try it online!

# 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

Try it online!

• this isn't right, because Julia is using the sample standard deviation calculation (dividing by n-1) rather than the population std (dividing by n) as required in the problem. Multiplying by (n-1)/n wouldn't fix it either, because when dividing by n-1, NaN is produced. I ran into the same problems when trying to do this in R and haven't given it thought since. Jan 5, 2018 at 17:30
• That didn't even occur to me. I added an alternate solution with the correct std deviation.
– gggg
Jan 5, 2018 at 20:35
• Oct 6, 2021 at 15:31

### Scala 208202 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
• For me "Vector(-56, -4, 28, -16, -14)" is wrong
– user58988
Jan 6, 2018 at 10:38
• @RosLuP: Why is it wrong? Jan 7, 2018 at 0:31
• Yes you are right if input is "Vector(64, 8, 4, 32, 16, 2)" ( i confuse the input)
– user58988
Jan 7, 2018 at 12:50

# Jelly, 27 bytes

_ÆmÆḊ÷L½$Wẋ9SPÆmÆṁIṢṂṀÇ9ƭ€ Try it online! ## How it works _ÆmÆḊ÷L½$ - 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

Try it online!

# Factor + math.unicode, 90 bytes

[| s | s Σ s Π s mean s median s differences s [ > ] sort s minmax s population-std .s ]

Try it online!

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.

# Pyt, 39 bytes

←ĐĐĐĐĐĐĐŞ⇹Ʃ3ȘΠ4Șµ5Ș₋⇹6Ș↕⇹7ȘṀ↔ĐĐµ-²Ʃ⇹Ł/√

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

Try it online!

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
ĐĐµ-²Ʃ⇹Ł/√               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 = n such that half the elements of l are smaller or equal to n and half the elements of l are greater or equal to n

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,

Try it online.

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.

Try it online.

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