5
$\begingroup$

How to divide each element of a list by its position?

I have a list

t1 = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

and want to divide each element by its Position yielding

{2, 3/2, 5/3, 7/4, 11/5, 13/6, 17/7, 19/8, 23/9, 29/10}

It can be done by

Flatten[#/Flatten[Position[t1, #]] & /@ t1]

which looks awful. Any better ideas (without using Range)?

$\endgroup$
1
  • 1
    $\begingroup$ Table[t1[[i]]/i, {i, Length[t1]}] $\endgroup$ – Christopher Lamb Jun 11 '20 at 17:57
6
$\begingroup$
MapIndexed[#1/First[#2] &, t1]

or

#/Range[Length[#]] &[t1]

All return:

(* Out: {2, 3/2, 5/3, 7/4, 11/5, 13/6, 17/7, 19/8, 23/9, 29/10} *)
$\endgroup$
1
  • $\begingroup$ t1/Range@Length@t1 is a great code-golf version of this! It manages for repeated values, too! AND keeps the ordering! Nice work, MarcoB! $\endgroup$ – CA Trevillian Jun 12 '20 at 21:10
5
$\begingroup$

For this specific list (list of primes) one can do:

Array[ Prime[#]/# &, 10]

or in more general case:

Array[ t1[[#]]/# &, 10]

Nonetheless I still find Range the most efficient and elegant:

t1/Range[10]
 {2, 3/2, 5/3, 7/4, 11/5, 13/6, 17/7, 19/8, 23/9, 29/10}

or t1/Range[ Length[t1]].

$\endgroup$
5
$\begingroup$

For the particular t1 in OP:

t1 / PrimePi[t1]
 {2, 3/2, 5/3, 7/4, 11/5, 13/6, 17/7, 19/8, 23/9, 29/10}

In general,

(i = 1; Map[# / i++ &]) @ t1
{2, 3/2, 5/3, 7/4, 11/5, 13/6, 17/7, 19/8, 23/9, 29/10}
lookMaNoRange = Accumulate[1 & /@ #] &;
t1 / lookMaNoRange[t1]
{2, 3/2, 5/3, 7/4, 11/5, 13/6, 17/7, 19/8, 23/9, 29/10}
lookMaNoRange2 = (i = 1; Map[i++ &]);
t1 / lookMaNoRange2[t1]
{2, 3/2, 5/3, 7/4, 11/5, 13/6, 17/7, 19/8, 23/9, 29/10}

etc...

$\endgroup$
2
  • $\begingroup$ lookMaNoRange <— that made me laugh hehehe $\endgroup$ – MarcoB Jun 12 '20 at 2:14
  • $\begingroup$ You are a fox! Cunning as ever! $\endgroup$ – user57467 Jun 12 '20 at 12:54
4
$\begingroup$
KeyValueMap[Splice[#1/#2]&, PositionIndex@t1]

or

KeyValueMap[#1/#2&, PositionIndex@t1]//Flatten

{2, 3/2, 5/3, 7/4, 11/5, 13/6, 17/7, 19/8, 23/9, 29/10}

$\endgroup$
2
  • 1
    $\begingroup$ Though solution no. 1 does not not work in my version, I learnt new things from no. 2. Great! $\endgroup$ – user57467 Jun 12 '20 at 12:48
  • 1
    $\begingroup$ Nice work. This manages for repeated values (though changes the ordering) unlike my solution using PositionIndex $\endgroup$ – CA Trevillian Jun 12 '20 at 21:04
3
$\begingroup$

This might only work if there’s no duplicates

PositionIndex@t1//{Keys[#],Values[#]}&//Transpose//(#[[1]]/#[[2,1]])&/@#&
$\endgroup$
1
  • $\begingroup$ Wow! Your style is different! $\endgroup$ – user57467 Jun 12 '20 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.