1

My own class methods do not work when I check how my function 'linker' operates. These methods return None value.

When I run these methods in the interactive mode, they work and each returns a new node linked to the root. Why do these methods not work when I run the function 'linker'?

Node is defined as

class node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None


    def insertL(self, data):
        self.left = node(data)
        return self.left

    def insertR(self, data):
        self.right = node(data)
        return self.right




def linker(root, lst):
    import random

    seq = ['left', 'right', 'nither', 'either']
    res = random.choices(seq,(0.1,0.3,0.1,0.6), k=1)
    if lst:
        l=random.choice(lst)

        if res == 'left':
            root=root.insertL(l)
            lst.remove(l)
            return root, lst
        elif res == 'right':
            root=root.insertR(l)
            lst.remove(l)
            return root,lst
        elif res == 'nither':
            return root,lst
        elif res == 'either':
            nodes = [root.insertL(l)]
            lst.remove(l)
            l2=random.choice(lst)
            nodes+=[root.insertR(l2)]
            lst.remove(l2)
            return nodes, lst
    else: 
        return root, lst
aspiring
  • 357
  • 2
  • 3
  • 11
  • There is plenty to be said about this code: your formatting is really all over the place, and makes it hard to follow your code. importing locally (as you do in linker) is almost never a necessity and you should not do it until you understand the circumstances under which it is necessary. placing the return on the same line as the else: is also uncommon and makes your code harder to read. Last but not least: your formatting contributes to your porblem. insertL and insertR are indented too deep. They need to come to the same level as __init__. – deets Nov 18 '18 at 11:28
  • @deets I made the edits. – aspiring Nov 18 '18 at 11:40
  • I found the answer myself. random.choices gives the list ['either'] or ['left'] etc . Then this list (containing one element) is compared with the string 'either' or 'left' ,etc in the if-section. That's why the function returns None. – aspiring Nov 18 '18 at 12:02

0 Answers0