[Answered ]-How to solve this complex recursive problem, pyramid point system

1šŸ‘

āœ…

I think your problem could be that you arenā€™t setting the child(s) of profile to now have parent as itā€™s/their parent, unless children with parents canā€™t also be parents in your system (which I do not believe to be the case).

Alternatively (or possibly together with the previous), you may want to just do parent = profile.parent rather than parent = profile.parent.get_profile().

EDIT: And I see that you did indeed switch to something of that second form, though using user instead of profile.

Anyway, since each user can have multiple children (as you stated in a comment on another answer), you might want to keep track of each userā€™s child from within that userā€™s object. Something likeā€¦

parent = user.parent
user.parent = parent.parent
parent.parent = user

children = user.children

for child in children:
    child.parent = parent

user.children = parent.children

for child in user.children:
    if child is user:
        child = parent

    child.parent = user

parent.children = children

for child in user.parent.children:
    if child is parent:
        child = user

This probably needs refactoring, though, and I may have missed something.

šŸ‘¤JAB

1šŸ‘

[correction according to your comment]

If the result of the ā€œmoveā€ never intends to change the topology of the tree(i.e. when X becomes the parent of its old parent Y, it gives all its children to Y), then the simplest might be to decouple the notion ā€œpyramid nodesā€ from the ā€œusersā€, with one-to-one relationship. Then if the ā€˜swapā€™ operation does not change the topology of the tree, you would only need to swap the mapping between ā€˜nodeA <=> userAā€™ and ā€˜nodeB <=> userBā€™ so they become ā€˜nodeA <=> userBā€™ and ā€˜nodeB <=> userAā€™.

Since the topology of the tree does not change, this would automagically take care of the children having a correct parent. The downside, of course, is that you no longer can directly find out the ā€˜parentā€™ from a user record and would need to go via the nodes.

No code as I am not sure of your application details ā€“ but hopefully if this is applicable it should be easy enough to turn into code.

šŸ‘¤Andrew Y

Leave a comment