user9042207
user9042207

Reputation: 111

iPython Splitting

I have the following numbers in an array:

a = [1,2,3,4,5,6,7,8,9,10]

I want to create two new arrays with half of this array in each. I have attempted the following:

mid = len(a) / 2
a1 = (mid * ctypes.py_object)()
a2 = (mid * ctypes.py_object)()
for i in range(mid):
    a1[i] = a[i]

This works just fine for the first array. What I am having trouble with is the second array. I have tried:

for j in range(mid, len(a)):
    a2[j] = a[j]

I get an invalid index error. What am I doing wrong?

Thanks

Upvotes: 0

Views: 36

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155674

len(a) // 2 computes the floor of len(a) divided by 2. Problem is, if a has an odd length, say, 3, you create a1 and a2 as length 1 arrays (since 3 // 2 == 1), so trying to put the remainder of a (2 elements) into a2 (1 element) indexes out of bounds.

A simple solution is to define a2 not as mid elements long, but as "remainder" elements long, e.g.:

mid = len(a) // 2
remainder = len(a) - mid
a1 = (mid * ctypes.py_object)()
a2 = (remainder * ctypes.py_object)()

You could inline the remainder computation if desired (a2 = ((len(a) - mid) * ctypes.py_object)()), I just split it out for clarity in the example.

An equivalent approach would be to simply round up for the remainder calculation, e.g. remainder = (len(a) + 1) // 2; the effect is the same, I'm just mentioning this as an alternative for illustration.

Upvotes: 2

Will_Panda
Will_Panda

Reputation: 534

You can create the arrays as below.

a = [1,2,3,4,5,6,7,8,9,10]

mid = len(a) / 2
a1 = a[:mid]
a2 = a[mid:]

Upvotes: 0

Related Questions