Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I started to learn python from scratch. I got some issues while doing the following problem.

I have the following vector ,x_vector = (0,1,2,3,4,5,6,7,8,9). Using this vector, I need to create this new vector x1 = (-0.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5).

Basically the desired vector should have first element -0.5, mid points between each elements and the last element +0.5.

The code I tried so far as follows:

import numpy as np

x_vector=np.array([0,1,2,3,4,5,6,7,8,9])

x=len(x_vector)

mid=np.zeros(x+1)

for i in range (0,x):

    if i==0 :

        mid[i]= x_vector[i]-0.5

    else :

        mid[i]=(x_vector[i] + x_vector[i+1])/2

        i +=1

Seems like this doesn't give the desired output. Can you one help me to figure out what can I do to get correct output?

1 Answer

0 votes
by (25.1k points)

You can use itertools tee module. Like this

from itertools import tee

def pairwise(iterable):

    a, b = tee(iterable)

    next(b, None)

    return zip(a, b)

res = []

res.append(min(x_vector)-0.5)

res.append(max(x_vector)+0.5)

res.extend([np.mean(z) for z in pairwise(x_vector)])

sorted(res)

Browse Categories

...