Ask Your Question
0

A function which sweep the indexes and doesn't stop at the first encounter

asked 2023-04-09 19:44:13 +0100

Cyrille gravatar image

updated 2023-04-09 19:46:45 +0100

I would like to understand why the following code doesn't work

p=[-100,10,10,10,10,10,10,10,10,10,10]
[x/(1+.02)^(p.index(x)) for x in p]

what I was expecting is that for each $x$ (p.index(x)) would be an other index. I remember that since $10$ is of multiplicity $9$, (p.index(x)) is the index of the first occurence of $9$. So I ask if there is a function that sweep the index of all $x$ with or without multiplicity.

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
0

answered 2023-04-09 23:21:09 +0100

Emmanuel Charpentier gravatar image

Unless I'm mistaken, you're looking at :

sage: [p[i]*1.2^-i for i in range(len(p))]
[-100.000000000000,
 8.33333333333333,
 6.94444444444444,
 5.78703703703704,
 4.82253086419753,
 4.01877572016461,
 3.34897976680384,
 2.79081647233653,
 2.32568039361378,
 1.93806699467815,
 1.61505582889846]

Pourquoi faire simple quand on peut faire compliqué ?

HTH,

edit flag offensive delete link more

Comments

CA je savais faire Emmanuel. je me demandais si c'était quelque chose de possible avec une compréhension de liste. Ca semble une fonction normale. Si la comprehension de liste balaye tous les éléments de la liste elle devrait être capable d'isoler leur rang. Ce n'était qu'un exemple.

Cyrille gravatar imageCyrille ( 2023-04-10 08:24:59 +0100 )edit

The call to p.index(x) returns the first occurence of x in p (so 1) and it takes linear time in the size of the list.

sage: p=[-100,10,10,10,10,10,10,10,10,10,10]
sage: [p.index(x) for x in p]
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

You can also get the index of the next occurence of x, specifying the index at which to start the search

sage: q = [10,20,10,3,4,5,10]
sage: q.index(10)
0
sage: q.index(10, 1)
2
sage: q.index(10, 3)
6

But if you want to know all indices of x, I suggest

sage: [i for i, x in enumerate(q) if x == 10]
[0, 2, 6]
David Coudert gravatar imageDavid Coudert ( 2023-04-10 13:56:23 +0100 )edit

So for your initial example, you can write

sage: [x*1.2^-i for i, x in enumerate(p)]
[-100.000000000000,
 8.33333333333333,
 6.94444444444445,
 5.78703703703704,
 4.82253086419753,
 4.01877572016461,
 3.34897976680384,
 2.79081647233653,
 2.32568039361378,
 1.93806699467815,
 1.61505582889846]
David Coudert gravatar imageDavid Coudert ( 2023-04-10 13:57:16 +0100 )edit

Thanks David you answered my question. But, this elegant solution is slow Wall time: 82.3 µs on my computer. Emmanuel's one is Wall time: 14.5 µs

Cyrille gravatar imageCyrille ( 2023-04-12 10:39:53 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-04-09 19:44:13 +0100

Seen: 236 times

Last updated: Apr 09 '23