Frage

Ich habe eine hierarchische Organisation, die ein Baum ist, in dem der Knoten ein Kind ist, wenn der Elternteil das Kind sponsert.Es scheint, dass ich den Baum mit diesem Code durchqueren kann generasacodicetagpre.

Mit dem oben genannten können ich die Organisation eines Benutzers nur von bekommen

downline=user.get_team(user, [])

ist aber eine effizientere Weise, da ich dies oft für eine einzelne Anfrage tun muss und dass viel Rekursion ineffizient sein könnte?Oder wird der Code in Ordnung sein, da er den Baum richtig durchqueren kann?In meiner ersten Version habe ich drei Variablen verwendet und fand ich, dass ich den Code auf nur zwei Variablen anordnen konnte, anstatt davon: generasacodicetagpre.

Ich fand heraus, dass die Teamliste-Variable nicht wirklich benötigt wurde, also habe ich es entfernt.So wie ich es tat, war zuerst mit einer Variablen zu viele:

people = user.downline(user, [], [])

War es hilfreich?

Lösung

Yes, there is a more efficient way to do it, depending on your computational tradeoffs.

You are currently doing a depth-first traversal of your tree, a perfectly fine approach. You could add some speed by caching results at the expense of some RAM usage, so:

if person.id in downline_cache:
      team.append(downline_cache[person.id])
else:
      downline_cache[person.id] = results
      team.append(results)

If the tree is fairly small, you could just cache the whole thing upfront, once per thread. That takes more RAM than what you're doing, but is much faster than doing a depth-first traversal every time you care what the results are. A lot depends on your usage patterns and the amount of data you're storing.

If you use a cache, you must make sure you have some way to deal with the underlying data changing, either with timeouts and 'eventually correct' type guarantees, or keeping track of when and how you must wipe the cache, or elements of the cache.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top