Processing math: 100%
Ask Your Question
0

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

asked 2 years ago

Cyrille gravatar image

updated 2 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
0

answered 2 years ago

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,

Preview: (hide)
link

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 ( 2 years ago )

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 ( 2 years ago )

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 ( 2 years ago )

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 ( 2 years ago )

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: 2 years ago

Seen: 379 times

Last updated: Apr 09 '23