0
def q(s):
    n = len(s)
    v = numpy.zeros(n, dtype=float)

s is a vector containing however many elements I wish ([s0,s1,s2,....,sn-2,sn-1]) , and I intend to then create an array (initial full of zeros) that is of the same size as s.

My aim is to then to change the zero elements in this array to [s1/s0 , s2/s1 , s3/s2..., sn-1/sn-2].

I understand that a for loop is required, but I am finding it difficult to program this. Could anybody offer a hand? Thank you.

1
  • Please try something first, then if you're stuck tell us what you tried and where you got stuck and the Python community here at Stack Overflow would love to help. Commented Feb 8, 2014 at 18:04

2 Answers 2

1

You don't need to create an array of zeros first.

[b / a for a, b in zip(s, s[1:])]

Explanation

s your list, s[1:] is you list except for the first element.

zip puts them together in pairs, like [[s0, s1], [s1, s2],... [sn-2, sn-1]].

Then you just divide the second element of each sublist by the first.

Sign up to request clarification or add additional context in comments.

2 Comments

@AshwiniChaudhary, you are correct. I changed the order of division instead.
Hello, thanks for your help and I can see that this would work. But for this function in particular, I want to create an array of zeros initially; and then change the zeros. (Even though I know its long winded and unnecessary!)
1

You don't need an explicit loop if you're using a NumPy array:

>>> import numpy as np
>>> a = np.array([10, 20, 30, 40, 50], dtype=float)
>>> a[1:]/a[:-1]
array([ 2.        ,  1.5       ,  1.33333333,  1.25      ])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.