Le 23/12/2004 20:53, dans , « Jean-Sebastien Mouret » a écrit :
en gros:
def append_word(tree, word): if len(word): char = word[0] if not tree.has_key(char): tree[char] = {} append_word(tree[char], word[1:]) [etc]
Merci beaucoup (et à Michel Claveau) c'est exactement ce que je n'arrivais pas écrire...
je suis soufflé par la concision de Python :-)
je vais essayer maintenant de construire mon arbre à partir d'un fichier texte. Ça ne devrait pas poser trop de problème.
Marc (newbie)
guignot
#!/usr/bin/python
class node : def __init__(self) : self.desc = {} self.IsWord = False def add(self,word): print "add",self, word if word == "" : self.IsWord = True;return initiale = word[0] if not initiale in self.desc.keys() : self.desc[initiale] = node() self.desc[initiale].add(word[1:]) def affiche(self) : print self, self.IsWord for i in self.desc.keys() : self.desc[i].affiche() def cherche(self,word) : if word == "" : return self.IsWord initiale = word[0] if not initiale in self.desc.keys() : return False return self.desc[initiale].cherche(word[1:])
class node :
def __init__(self) :
self.desc = {}
self.IsWord = False
def add(self,word):
print "add",self, word
if word == "" : self.IsWord = True;return
initiale = word[0]
if not initiale in self.desc.keys() : self.desc[initiale] = node()
self.desc[initiale].add(word[1:])
def affiche(self) :
print self, self.IsWord
for i in self.desc.keys() :
self.desc[i].affiche()
def cherche(self,word) :
if word == "" : return self.IsWord
initiale = word[0]
if not initiale in self.desc.keys() : return False
return self.desc[initiale].cherche(word[1:])
class node : def __init__(self) : self.desc = {} self.IsWord = False def add(self,word): print "add",self, word if word == "" : self.IsWord = True;return initiale = word[0] if not initiale in self.desc.keys() : self.desc[initiale] = node() self.desc[initiale].add(word[1:]) def affiche(self) : print self, self.IsWord for i in self.desc.keys() : self.desc[i].affiche() def cherche(self,word) : if word == "" : return self.IsWord initiale = word[0] if not initiale in self.desc.keys() : return False return self.desc[initiale].cherche(word[1:])