Using set to count if two Tree have same values nodesDoes Python have an ordered set?'Queue' object has no attribute 'size'How to serialize a tree class object structure into json file format?retrieve from a binary search treeError when resample dataframe with pythonDifficulty to create a function groupby in pythonI have a recursive function to validate tree graph and need a return conditionlinkedlist node insertion and printing all the nodes--pythonDelete First Node From Python Linked Listslicing pandas dataframe encounter KeyError: 'n_tokens_content', how to locate the bad rows efficiently?

Given a 32 bit number, what is an efficient way to scale each byte by a certain factor?

Graduate student with abysmal English writing skills, how to help

GDPR rights when subject dies; does family inherit subject rights?

[Future]Historical experience as a guide to warship design?

Can Jimmy hang on his rope?

Are there any sports for which the world's best player is female?

When I press the space bar it deletes the letters in front of it

What happens to unproductive professors?

What is the parallel of Day of the Dead with Stranger things?

Efficiently defining a SparseArray function

Is this a reference to the film Alien in the novel 2010 Odyssey Two?

What's the point of having a RAID 1 configuration over incremental backups to a secondary drive?

How can a dictatorship government be beneficial to a dictator in a post-scarcity society?

Is there a nice way to implement a conditional type with default fail case?

Why does every calorie tracking app give a different target calorie count for the same goals?

LED glows slightly during soldering

Received a dinner invitation through my employer's email, is it ok to attend?

The joke office

Why does wrapping Aluminium foil around my food help it keep warm, aluminium be good conductor should have no effect?

Chorophyll and photosynthesis in plants with coloured leaves

A horrible Stockfish chess engine evaluation

How to tell someone I'd like to become friends without letting them think I'm romantically interested in them?

Why do you use the "park" gear to park a car and not only the handbrake?

Why do we need common sense in AI?



Using set to count if two Tree have same values nodes


Does Python have an ordered set?'Queue' object has no attribute 'size'How to serialize a tree class object structure into json file format?retrieve from a binary search treeError when resample dataframe with pythonDifficulty to create a function groupby in pythonI have a recursive function to validate tree graph and need a return conditionlinkedlist node insertion and printing all the nodes--pythonDelete First Node From Python Linked Listslicing pandas dataframe encounter KeyError: 'n_tokens_content', how to locate the bad rows efficiently?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5















In "def same_child_values". I am trying to compare two trees to see if the other tree has same value nodes to the primary tree.children. In this case I am using a set to compare them. But in my code when the tree depth is greater than 1 then my code cannot add the nodes into the set correctly. Can anyone help me?



class Tree:
'''Tree ADT; nodes may have any number of children'''

def __init__(self: 'Tree',
item: object =None, children: list =None):
'''Create a node with item and any number of children'''

self.item = item
if not children:
self.children = []
else:
self.children = children[:]

def __repr__(self: 'Tree') -> str:
'''Return representation of Tree as a string'''

if self.children:
return 'Tree(0, 1)'.format(repr(self.item), repr(self.children))
else:
return 'Tree()'.format(repr(self.item))

def is_leaf(self: 'Tree') -> bool:
'''Return True iff this Tree node is a leaf (has no children).'''

return self.children == []

def remove_equal(self: 'Tree') -> None:
'''Remove every child that has the same item as its parent;
any children of a removed node n become children of an ancestor of n.

>>> t = Tree(1, [Tree(2, [Tree(1), Tree(2)]), Tree(1)])
>>> t.remove_equal()
>>> repr(t)
'Tree(1, [Tree(2, [Tree(1)])])'
>>> t = Tree(4, [Tree(4, [Tree(6)])])
>>> t.remove_equal()
>>> repr(t)
'Tree(4, [Tree(6)])'
>>> t = Tree(4, [Tree(4, [Tree(4, [Tree(4)])])])
>>> t.remove_equal()
>>> repr(t)
'Tree(4)'
>>> t = Tree(4, [Tree(4, [Tree(4, [Tree(6), Tree(7)]), Tree(8)]), Tree(9)])
>>> t.remove_equal()
>>> repr(t)
'Tree(4, [Tree(6), Tree(7), Tree(8), Tree(9)])'
'''
new_children = []
for c in self.children:
c.remove_equal()
if not c.item == self.item:
new_children.append(c)
else:
new_children.extend(c.children)
self.children = new_children



# Q1: Complete this method (This was the last part of last week's lab.
# If you did not have a chance to finish it last week, work on it today.)


This is the function I need to finish



 def same_child_values(self: 'Tree', other: 'Tree') -> None:
'''
Return True iff the other tree node given has all the same values for its children.
The values do not have to occur the same number of times.
We are only looking at values of the immediate children, not the descendants.

Hint: Use sets to compare a list of all children keys
More on sets - https://www.programiz.com/python-programming/set

>>> t = Tree(4, [Tree(6), Tree(7), Tree(8), Tree(9)])
>>> t2 = Tree(5, [Tree(6), Tree(7, [Tree(8, [Tree(9)])])])
>>> t3 = Tree(6, [Tree(7), Tree(8), Tree(6), Tree(6), Tree(9)])
>>> t4 = Tree(7, [Tree(7), Tree(7), Tree(6)])
>>> t.same_child_values(t2)
False
>>> t.same_child_values(t3)
True
>>> t4.same_child_values(t2)
True
'''
a = set()
b = set()


This is my code:



 for c in self.children:
a.add(c.item)
c.same_child_values(other)
for d in other.children:
b.add(d.item)
self.same_child_values(d)
return b


if my "other" tree is t3 I expect to see in my set()



my set() = 8, 9, 6, 7


if my "other" tree is t2 I expect to see in my set()



my set() = 8, 9, 6, 7, 5


but my code output for t2 is



my set() = 6, 7


(By the way for set() in python should it sort the value by default?)



Please help.










share|improve this question



















  • 1





    sets are unordered - the display order is not guaranteed to stay like this over different set implementations - it might change if you add 100 other values depending on the internal buckets used. it might even change between print() statements - you never know.

    – Patrick Artner
    Aug 1 '18 at 5:31


















5















In "def same_child_values". I am trying to compare two trees to see if the other tree has same value nodes to the primary tree.children. In this case I am using a set to compare them. But in my code when the tree depth is greater than 1 then my code cannot add the nodes into the set correctly. Can anyone help me?



class Tree:
'''Tree ADT; nodes may have any number of children'''

def __init__(self: 'Tree',
item: object =None, children: list =None):
'''Create a node with item and any number of children'''

self.item = item
if not children:
self.children = []
else:
self.children = children[:]

def __repr__(self: 'Tree') -> str:
'''Return representation of Tree as a string'''

if self.children:
return 'Tree(0, 1)'.format(repr(self.item), repr(self.children))
else:
return 'Tree()'.format(repr(self.item))

def is_leaf(self: 'Tree') -> bool:
'''Return True iff this Tree node is a leaf (has no children).'''

return self.children == []

def remove_equal(self: 'Tree') -> None:
'''Remove every child that has the same item as its parent;
any children of a removed node n become children of an ancestor of n.

>>> t = Tree(1, [Tree(2, [Tree(1), Tree(2)]), Tree(1)])
>>> t.remove_equal()
>>> repr(t)
'Tree(1, [Tree(2, [Tree(1)])])'
>>> t = Tree(4, [Tree(4, [Tree(6)])])
>>> t.remove_equal()
>>> repr(t)
'Tree(4, [Tree(6)])'
>>> t = Tree(4, [Tree(4, [Tree(4, [Tree(4)])])])
>>> t.remove_equal()
>>> repr(t)
'Tree(4)'
>>> t = Tree(4, [Tree(4, [Tree(4, [Tree(6), Tree(7)]), Tree(8)]), Tree(9)])
>>> t.remove_equal()
>>> repr(t)
'Tree(4, [Tree(6), Tree(7), Tree(8), Tree(9)])'
'''
new_children = []
for c in self.children:
c.remove_equal()
if not c.item == self.item:
new_children.append(c)
else:
new_children.extend(c.children)
self.children = new_children



# Q1: Complete this method (This was the last part of last week's lab.
# If you did not have a chance to finish it last week, work on it today.)


This is the function I need to finish



 def same_child_values(self: 'Tree', other: 'Tree') -> None:
'''
Return True iff the other tree node given has all the same values for its children.
The values do not have to occur the same number of times.
We are only looking at values of the immediate children, not the descendants.

Hint: Use sets to compare a list of all children keys
More on sets - https://www.programiz.com/python-programming/set

>>> t = Tree(4, [Tree(6), Tree(7), Tree(8), Tree(9)])
>>> t2 = Tree(5, [Tree(6), Tree(7, [Tree(8, [Tree(9)])])])
>>> t3 = Tree(6, [Tree(7), Tree(8), Tree(6), Tree(6), Tree(9)])
>>> t4 = Tree(7, [Tree(7), Tree(7), Tree(6)])
>>> t.same_child_values(t2)
False
>>> t.same_child_values(t3)
True
>>> t4.same_child_values(t2)
True
'''
a = set()
b = set()


This is my code:



 for c in self.children:
a.add(c.item)
c.same_child_values(other)
for d in other.children:
b.add(d.item)
self.same_child_values(d)
return b


if my "other" tree is t3 I expect to see in my set()



my set() = 8, 9, 6, 7


if my "other" tree is t2 I expect to see in my set()



my set() = 8, 9, 6, 7, 5


but my code output for t2 is



my set() = 6, 7


(By the way for set() in python should it sort the value by default?)



Please help.










share|improve this question



















  • 1





    sets are unordered - the display order is not guaranteed to stay like this over different set implementations - it might change if you add 100 other values depending on the internal buckets used. it might even change between print() statements - you never know.

    – Patrick Artner
    Aug 1 '18 at 5:31














5












5








5


1






In "def same_child_values". I am trying to compare two trees to see if the other tree has same value nodes to the primary tree.children. In this case I am using a set to compare them. But in my code when the tree depth is greater than 1 then my code cannot add the nodes into the set correctly. Can anyone help me?



class Tree:
'''Tree ADT; nodes may have any number of children'''

def __init__(self: 'Tree',
item: object =None, children: list =None):
'''Create a node with item and any number of children'''

self.item = item
if not children:
self.children = []
else:
self.children = children[:]

def __repr__(self: 'Tree') -> str:
'''Return representation of Tree as a string'''

if self.children:
return 'Tree(0, 1)'.format(repr(self.item), repr(self.children))
else:
return 'Tree()'.format(repr(self.item))

def is_leaf(self: 'Tree') -> bool:
'''Return True iff this Tree node is a leaf (has no children).'''

return self.children == []

def remove_equal(self: 'Tree') -> None:
'''Remove every child that has the same item as its parent;
any children of a removed node n become children of an ancestor of n.

>>> t = Tree(1, [Tree(2, [Tree(1), Tree(2)]), Tree(1)])
>>> t.remove_equal()
>>> repr(t)
'Tree(1, [Tree(2, [Tree(1)])])'
>>> t = Tree(4, [Tree(4, [Tree(6)])])
>>> t.remove_equal()
>>> repr(t)
'Tree(4, [Tree(6)])'
>>> t = Tree(4, [Tree(4, [Tree(4, [Tree(4)])])])
>>> t.remove_equal()
>>> repr(t)
'Tree(4)'
>>> t = Tree(4, [Tree(4, [Tree(4, [Tree(6), Tree(7)]), Tree(8)]), Tree(9)])
>>> t.remove_equal()
>>> repr(t)
'Tree(4, [Tree(6), Tree(7), Tree(8), Tree(9)])'
'''
new_children = []
for c in self.children:
c.remove_equal()
if not c.item == self.item:
new_children.append(c)
else:
new_children.extend(c.children)
self.children = new_children



# Q1: Complete this method (This was the last part of last week's lab.
# If you did not have a chance to finish it last week, work on it today.)


This is the function I need to finish



 def same_child_values(self: 'Tree', other: 'Tree') -> None:
'''
Return True iff the other tree node given has all the same values for its children.
The values do not have to occur the same number of times.
We are only looking at values of the immediate children, not the descendants.

Hint: Use sets to compare a list of all children keys
More on sets - https://www.programiz.com/python-programming/set

>>> t = Tree(4, [Tree(6), Tree(7), Tree(8), Tree(9)])
>>> t2 = Tree(5, [Tree(6), Tree(7, [Tree(8, [Tree(9)])])])
>>> t3 = Tree(6, [Tree(7), Tree(8), Tree(6), Tree(6), Tree(9)])
>>> t4 = Tree(7, [Tree(7), Tree(7), Tree(6)])
>>> t.same_child_values(t2)
False
>>> t.same_child_values(t3)
True
>>> t4.same_child_values(t2)
True
'''
a = set()
b = set()


This is my code:



 for c in self.children:
a.add(c.item)
c.same_child_values(other)
for d in other.children:
b.add(d.item)
self.same_child_values(d)
return b


if my "other" tree is t3 I expect to see in my set()



my set() = 8, 9, 6, 7


if my "other" tree is t2 I expect to see in my set()



my set() = 8, 9, 6, 7, 5


but my code output for t2 is



my set() = 6, 7


(By the way for set() in python should it sort the value by default?)



Please help.










share|improve this question
















In "def same_child_values". I am trying to compare two trees to see if the other tree has same value nodes to the primary tree.children. In this case I am using a set to compare them. But in my code when the tree depth is greater than 1 then my code cannot add the nodes into the set correctly. Can anyone help me?



class Tree:
'''Tree ADT; nodes may have any number of children'''

def __init__(self: 'Tree',
item: object =None, children: list =None):
'''Create a node with item and any number of children'''

self.item = item
if not children:
self.children = []
else:
self.children = children[:]

def __repr__(self: 'Tree') -> str:
'''Return representation of Tree as a string'''

if self.children:
return 'Tree(0, 1)'.format(repr(self.item), repr(self.children))
else:
return 'Tree()'.format(repr(self.item))

def is_leaf(self: 'Tree') -> bool:
'''Return True iff this Tree node is a leaf (has no children).'''

return self.children == []

def remove_equal(self: 'Tree') -> None:
'''Remove every child that has the same item as its parent;
any children of a removed node n become children of an ancestor of n.

>>> t = Tree(1, [Tree(2, [Tree(1), Tree(2)]), Tree(1)])
>>> t.remove_equal()
>>> repr(t)
'Tree(1, [Tree(2, [Tree(1)])])'
>>> t = Tree(4, [Tree(4, [Tree(6)])])
>>> t.remove_equal()
>>> repr(t)
'Tree(4, [Tree(6)])'
>>> t = Tree(4, [Tree(4, [Tree(4, [Tree(4)])])])
>>> t.remove_equal()
>>> repr(t)
'Tree(4)'
>>> t = Tree(4, [Tree(4, [Tree(4, [Tree(6), Tree(7)]), Tree(8)]), Tree(9)])
>>> t.remove_equal()
>>> repr(t)
'Tree(4, [Tree(6), Tree(7), Tree(8), Tree(9)])'
'''
new_children = []
for c in self.children:
c.remove_equal()
if not c.item == self.item:
new_children.append(c)
else:
new_children.extend(c.children)
self.children = new_children



# Q1: Complete this method (This was the last part of last week's lab.
# If you did not have a chance to finish it last week, work on it today.)


This is the function I need to finish



 def same_child_values(self: 'Tree', other: 'Tree') -> None:
'''
Return True iff the other tree node given has all the same values for its children.
The values do not have to occur the same number of times.
We are only looking at values of the immediate children, not the descendants.

Hint: Use sets to compare a list of all children keys
More on sets - https://www.programiz.com/python-programming/set

>>> t = Tree(4, [Tree(6), Tree(7), Tree(8), Tree(9)])
>>> t2 = Tree(5, [Tree(6), Tree(7, [Tree(8, [Tree(9)])])])
>>> t3 = Tree(6, [Tree(7), Tree(8), Tree(6), Tree(6), Tree(9)])
>>> t4 = Tree(7, [Tree(7), Tree(7), Tree(6)])
>>> t.same_child_values(t2)
False
>>> t.same_child_values(t3)
True
>>> t4.same_child_values(t2)
True
'''
a = set()
b = set()


This is my code:



 for c in self.children:
a.add(c.item)
c.same_child_values(other)
for d in other.children:
b.add(d.item)
self.same_child_values(d)
return b


if my "other" tree is t3 I expect to see in my set()



my set() = 8, 9, 6, 7


if my "other" tree is t2 I expect to see in my set()



my set() = 8, 9, 6, 7, 5


but my code output for t2 is



my set() = 6, 7


(By the way for set() in python should it sort the value by default?)



Please help.







python python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 7 '18 at 6:00









IdleCustard

1921 silver badge6 bronze badges




1921 silver badge6 bronze badges










asked Aug 1 '18 at 3:49









Zheng Lei PeiZheng Lei Pei

264 bronze badges




264 bronze badges







  • 1





    sets are unordered - the display order is not guaranteed to stay like this over different set implementations - it might change if you add 100 other values depending on the internal buckets used. it might even change between print() statements - you never know.

    – Patrick Artner
    Aug 1 '18 at 5:31













  • 1





    sets are unordered - the display order is not guaranteed to stay like this over different set implementations - it might change if you add 100 other values depending on the internal buckets used. it might even change between print() statements - you never know.

    – Patrick Artner
    Aug 1 '18 at 5:31








1




1





sets are unordered - the display order is not guaranteed to stay like this over different set implementations - it might change if you add 100 other values depending on the internal buckets used. it might even change between print() statements - you never know.

– Patrick Artner
Aug 1 '18 at 5:31






sets are unordered - the display order is not guaranteed to stay like this over different set implementations - it might change if you add 100 other values depending on the internal buckets used. it might even change between print() statements - you never know.

– Patrick Artner
Aug 1 '18 at 5:31













1 Answer
1






active

oldest

votes


















0














Is this what you are after?



def same_child_values(self, other):
return set([c.item for c in self.children]) == set([c.item for c in other.children])


The key element is in the docstring: "We are only looking at values of the immediate children, not the descendants."






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51625090%2fusing-set-to-count-if-two-tree-have-same-values-nodes%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Is this what you are after?



    def same_child_values(self, other):
    return set([c.item for c in self.children]) == set([c.item for c in other.children])


    The key element is in the docstring: "We are only looking at values of the immediate children, not the descendants."






    share|improve this answer



























      0














      Is this what you are after?



      def same_child_values(self, other):
      return set([c.item for c in self.children]) == set([c.item for c in other.children])


      The key element is in the docstring: "We are only looking at values of the immediate children, not the descendants."






      share|improve this answer

























        0












        0








        0







        Is this what you are after?



        def same_child_values(self, other):
        return set([c.item for c in self.children]) == set([c.item for c in other.children])


        The key element is in the docstring: "We are only looking at values of the immediate children, not the descendants."






        share|improve this answer













        Is this what you are after?



        def same_child_values(self, other):
        return set([c.item for c in self.children]) == set([c.item for c in other.children])


        The key element is in the docstring: "We are only looking at values of the immediate children, not the descendants."







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 0:52









        Pierre DPierre D

        4,7994 gold badges28 silver badges48 bronze badges




        4,7994 gold badges28 silver badges48 bronze badges


















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51625090%2fusing-set-to-count-if-two-tree-have-same-values-nodes%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현