Luca
Luca

Reputation: 11

reordering fixed legth array in python

I'm looking for the best way to perform this task in Python 2.x

I have an array of given size, with some element that have to stay at given position identified by attribute.

I have to remove an element from the array, and move all the non fixed elements to the top, and fill the missing bottom entry with a copy of the first entry.

Example

Starting array:

array[0]={property='dynamic', name='A'}
array[1]={property='dynamic', name='B'}
array[2]={property='fixed', name='C'}
array[3]={property='dynamic', name='D'}
array[4]={property='fixed', name='E'}
array[5]={property='dynamic', name='F'}

Remove one item

array[0]={property='dynamic', name='A'}
array[1]={property='dynamic', name='B'}
array[2]={property='fixed', name='C'}

array[4]={property='fixed', name='E'}
array[5]={property='dynamic', name='F'}

Move non fixed elements to top

array[0]={property='dynamic', name='A'}
array[1]={property='dynamic', name='B'}
array[2]={property='fixed', name='C'}
array[3]={property='dynamic', name='F'}
array[4]={property='fixed', name='E'}

end result filling last missing slot with top element

array[0]={property='dynamic', name='A'}
array[1]={property='dynamic', name='B'}
array[2]={property='fixed', name='C'}
array[3]={property='dynamic', name='F'}
array[4]={property='fixed', name='E'}
array[5]={property='dynamic', name='A'}

What could be the fastest way to do this ? (property, array size and elements are all dynamics)

Upvotes: 1

Views: 52

Answers (2)

codingCat
codingCat

Reputation: 2406

The answer from joel goldstick is probably your best bet. In some fashion you will need to move the rest of the list up to fill the gap. Here is an example the does the same thing programmatically:

removeIndex = 6                              //index to remove
for i in range(removeIndex+1, len(ary)-1):   //from next index to end of array
  ary[i-1] = ary[i]                          //move the item down one
ary[len(ary) - 1] = ary[0];                  //duplicate the first in the last position

Upvotes: 0

joel goldstick
joel goldstick

Reputation: 4493

I'm assuming you are using python lists

The first three lines just create a list with 3 items. Use your lists instead.

Pop removes the item at the index provided and returns its value a.append(a[0]) takes the first item, and appends it to the end of the list

>>> a.append(0)
>>> a.append(1)
>>> a.append(2)
>>> a
[0, 1, 2]
>>> p = a.pop(1)
>>> p
1
>>> a
[0, 2]
>>> a.append(a[0])
>>> a
[0, 2, 0]
>>> 

In my example a holds single values, but it could hold a dict like in your example. The code is the same

Upvotes: 1

Related Questions