6.3 Looping over the Neighbors of an Atom

Often it is not the bonds around the atoms that you wish to loop over, but the neighboring atoms. One way to do this would be to use the GetBonds method described in the previous section and use the GetNbr method of each OEBondBase to get the atom across the bond from the input atom.

#!/usr/bin/env python
# ch6-3.py
from openeye.oechem import *

def ShowNeighbors(atom):
    for bond in atom.GetBonds():
        nbor = bond.GetNbr(atom)
        print nbor.GetIdx(),
    print

mol = OEGraphMol()
OEParseSmiles(mol, "c1ccccc1")

for atom in mol.GetAtoms():
    print atom.GetIdx(),
    ShowNeighbors(atom)

However this can be done even more conveniently using the GetAtoms method of an OEAtomBase directly, which allows loops over the neighbor atoms.

#!/usr/bin/env python
# ch6-4.py
from openeye.oechem import *

def ShowNeighbors(atom):
    for nbor in atom.GetAtoms():
        print nbor.GetIdx(),
    print

mol = OEGraphMol()
OEParseSmiles(mol, "c1ccccc1")

for atom in mol.GetAtoms():
    print atom.GetIdx(),
    ShowNeighbors(atom)