add elements to indexed list locations

levent leventyilmaz at gmail.com
Sat Jun 17 03:22:59 EDT 2006


Thanks for the answers. Enumerating in reverse is indeed quite a smart
idea.

The fact is though, I overly simplified the task in the super-hero
example. In the real case, the dictionary keys are not necessarily the
indices for inserts; that is to say, the inserts do not necessarily
take place in some sorted order.

I think I was thinking more of a linked-list idea, where you do not
store the indices as integers to some random access array but rather as
pointers into list's nodes. Then the subsequent inserts would not hurt
previously stored pointers. For those who know a bit C++/STL here is a
sketch of the idea:

name_list  heros;
heros.push_back("clark");
// ... add the rest
indexed_name_list surnames;
surnames.push_back(
   make_pair(   find( heros.begin(), heros.end(), "clark"), "kent")   )
   );  // the find function returns an iterator to appropriate location
// ... add the rest

for_each(surnames.begin(), surnames.end(), insert_surnames)
// insert_surnames is a callback that receives a single indexed surname
// at a time and does the job, without affecting outer iterators.


I was wondering how to make indices as *robust* in Python... Any ideas?


PS: following is the compilable code-let of the task in C++

// ====================================================
#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <string>
#include <algorithm>

using namespace std;
typedef string name;
typedef pair<list<name>::iterator, string> indexed_name;

void insert_name( list<name>* into, indexed_name in ) {
   into->insert(in.first, in.second);
}

int main() {
   using namespace std;
   // Define super-heros (fathers ignored)
   list<name> heros;
   heros.push_back("super");
   heros.push_back("clark");
   heros.push_back("spider");
   heros.push_back("peter");
   heros.push_back("bat");
   heros.push_back("bruce");

   // Assign father names to proper son
   list<indexed_name> surnames;
   surnames.push_back(  // ++ is to have surname inserted _after_ the
name
      make_pair(++find(heros.begin(),heros.end(),"clark"),
string("kent"))
      );
   surnames.push_back(
      make_pair(++find(heros.begin(),heros.end(),"peter"),
string("parker"))
      );
   surnames.push_back(
      make_pair(++find(heros.begin(),heros.end(),"bruce"),
string("wayne"))
      );

   // Insert surnames succeeding appropriate heros
   for_each(surnames.begin(), surnames.end(),
      bind1st(ptr_fun(insert_name), &heros) );

   // Salute the heros
   copy(heros.begin(),heros.end(),ostream_iterator<string>(cout," "));
   cout << endl;
   return 0;
}

// =====================================================




More information about the Python-list mailing list