Jump to content

Python Bugs

Guest
Go to solution Solved by Garry Motorway,

Your FindNode function on line 105 is comparing number to the method GetNumber. You need to call it!

def FindNode(number):
    for val in tree:
        if (number == val.GetNumber):
            return val

should be

def FindNode(number):
    for val in tree:
        if (number == val.GetNumber()):
            return val

 

Here I am once again asking for your programming help.

 

I have no idea what's causing this bug but my code is trying to access None type objects.

 

Story Time:

I'm working on Breadth Search & recursive search with Python. I figured that part out. Right now I have some data type errors or something.

I'm used to C# where data types are explicitly stated so idk if I messed up mixing types.

 

Goal of program:

Find all nodes in the graph starting from Node 1.

 

I have 2 data structures.
"tree" which holds a series of "Node" which are outlined in the Node Class containing a value, the value of the Left Node & the value of the Right Node.

"output" is the second structure. This stores all the nodes found in the order they're found. There should be no duplicates as if a node is found, you shouldn't say you've found it again.

 

The graph is represented like so:

Spoiler

Node 1 has 2 & 3.

Node 2 has 4 & 5.

Node 3 has 4 & 5.

Node 4 has 5.
Node 5 has 1.

 

image.png.47b1c2854e570b2f6a6a5f4bde127b8a.png

As some nodes have only 1 "child" I standardized that right nodes would be the only ones that can be None. Therefore, every Left Node should contain a value.

 

And now I have an error saying a Left Node is of type none.

 
 
 
1
Spoiler

Note that Line numbers are not accurate to relevant code I present. All irrelevant code is completely bug free & not used in any way.

 


Traceback (most recent call last):
  File "F:/Documents/CTU/Python.py", line 217, in <module>
    main()
  File "F:/Documents/CTU/Python.py", line 82, in main
    BreadthSearch()
  File "F:/Documents/CTU/Python.py", line 98, in BreadthSearch
    BreadthCheck(val)
  File "F:/Documents/CTU/Python.py", line 129, in BreadthCheck
    print(left.GetNumber())
AttributeError: 'NoneType' object has no attribute 'GetNumber'

 

Program relevant code:

 
 
 
 
Spoiler

class Node():
    def __init__(self, number, left, right):
        self.number = number
        self.left = left
        self.right = right
    def GetNumber(self):
        return self.number
    def GetLeft(self):
        return self.left
    def GetRight(self):
        return self.right
        
tree = []

selectedDVDs = []

output = []

def main():

    CreateTree()
    for val in tree:
        print(val.GetNumber())
        print(val.GetLeft())
        print(val.GetRight())
        print ("\n \n Next MEME \n \n")
    while True:
        choice = DataCheck()
        if (choice == "1"):
            RecursiveSearch()
        if (choice == "2"):
            BreadthSearch()
        if (choice == "3"):
            ViewDVDs()
        if (choice == "4"):
            SelectDVDs()
        if (choice == "5"):
            ViewTotalAndAverageCosts(selectedDVDs)
        if (choice =="6"):
            ViewDVDSpecifics()

def BreadthSearch():

    for val in tree:
        if (val.GetNumber() == 1):
            Que.append(val)
            output.append(val)
            BreadthCheck(val)
            break
    for val in output:
        print (str(val.GetNumber()))

def FindNode(number):
    for val in tree:
        if (number == val.GetNumber):
            return val

def BreadthCheck(node):


    right = FindNode(node.GetRight())
    rightExists = False
    left = FindNode(node.GetLeft())
    leftExists = False

    for val in output:
        if right == val:
            rightExists = True
        if left == val:
            leftExists = True
        if (rightExists and leftExists) or (leftExists and right is None):
            break

    if (right is not None) and not rightExists:
        print(right.GetNumber())
        output.append(right)
        BreadthCheck(right)
    if not leftExists:
        print(left.GetNumber())
        output.append(left)
        BreadthCheck(left)

def RecursiveSearch():
    print ("void")

def DataCheck():
    print ("1. recursive search")
    print ("2. breadth search")


    return input("Enter your choice: ")

def CreateTree():
    tree.append(Node(1, 2, 3))
    tree.append(Node(2, 4, 5))
    tree.append(Node(3, 4, 5))
    tree.append(Node(4, 5, None))
    tree.append(Node(5, 1, None))

 

Complete copy/paste if you really want it. (Caution Language):

 
 
 
 
Spoiler

Now that you're here... can you really program without vulgar language?


# That stockholm syndrome I had for python...
# It has turned to contempt with the hidden
# variable types. I cannot declare types so...
# I have to just get fucked when I have a data type
# error.
from enum import Enum

class DVDType(Enum):
    Game = 1
    Word = 2
    Compiler = 3
    Spreadsheet = 4
    Dbase = 5
    Presentation = 6

class Node():
    def __init__(self, number, left, right):
        self.number = number
        self.left = left
        self.right = right
    def GetNumber(self):
        return self.number
    def GetLeft(self):
        return self.left
    def GetRight(self):
        return self.right
tree = []
root = None
currentNode = None

start = 0
end = 0
selectedDVDs = []

output = []
Que = []

def listValidDVDTypes():
    print (DVDType.Game)
    print (DVDType.Word)
    print (DVDType.Compiler)
    print (DVDType.Spreadsheet)
    print (DVDType.Dbase)
    print (DVDType.Presentation)


class DVD:
    def __init__(self, Name, Type, Cost):
        self.Name = Name
        self.Type = Type
        self.Cost = Cost

    def SetName (self, name):
        self.Name = name
    def SetType(self, type):
        self.Type = type

    def GetName(self):
        return self.Name
    def GetType(self):
        return self.Type
    def GetCost(self):
        return self.Cost

#class Manager(Employee):
#    def GetPay(self):
#        return self.Hours * 5

def main():

    CreateTree()
    for val in tree:
        print(val.GetNumber())
        print(val.GetLeft())
        print(val.GetRight())
        print ("\n \n Next MEME \n \n")
    while True:
        choice = DataCheck()
        if (choice == "1"):
            RecursiveSearch()
        if (choice == "2"):
            BreadthSearch()
        if (choice == "3"):
            ViewDVDs()
        if (choice == "4"):
            SelectDVDs()
        if (choice == "5"):
            ViewTotalAndAverageCosts(selectedDVDs)
        if (choice =="6"):
            ViewDVDSpecifics()

def BreadthSearch():

    for val in tree:
        if (val.GetNumber() == 1):
            Que.append(val)
            output.append(val)
            BreadthCheck(val)
            break
    for val in output:
        print (str(val.GetNumber()))

def FindNode(number):
    for val in tree:
        if (number == val.GetNumber):
            return val

def BreadthCheck(node):


    right = FindNode(node.GetRight())
    rightExists = False
    left = FindNode(node.GetLeft())
    leftExists = False

    for val in output:
        if right == val:
            rightExists = True
        if left == val:
            leftExists = True
        if (rightExists and leftExists) or (leftExists and right is None):
            break

    if (right is not None) and not rightExists:
        print(right.GetNumber())
        output.append(right)
        BreadthCheck(right)
    if not leftExists:
        print(left.GetNumber())
        output.append(left)
        BreadthCheck(left)

def RecursiveSearch():
    print ("void")

def DataCheck():
    print ("1. recursive search")
    print ("2. breadth search")


    return input("Enter your choice: ")

def CreateTree():
    tree.append(Node(1, 2, 3))
    tree.append(Node(2, 4, 5))
    tree.append(Node(3, 4, 5))
    tree.append(Node(4, 5, None))
    tree.append(Node(5, 1, None))

def ViewDVDs():
    for val in tree:
        print (str(val.GetName()))

def SelectDVDs():
    while True:
        dvdSelect = input("Enter DVD index to select. Enter x to exit.")
        if (dvdSelect == 'x'):
            return
        int(dvdSelect)
        for x in range(len(tree)):
            if (x == int(dvdSelect)):
                dvdAdd = tree[x]
                selectedDVDs.append(dvdAdd)

def ViewDVDSpecifics():
    while True:
        dvdSelect = input("Enter DVD index to view. Enter x to exit.")
        if (dvdSelect == 'x'):
            return
        int(dvdSelect)
        for x in range(len(tree)):
            if (x == int(dvdSelect)):
                print("name: " + str(tree[x].GetName()))
                print("cost: " + str(tree[x].GetCost()))
                print("Type: " + str(tree[x].GetType()))


def ViewTotalAndAverageCosts(passedList):
    dvdCount = len(passedList)
    totalCost = 0
    for val in passedList:
        totalCost = totalCost + val.GetCost()

    print ("total cost: " + str(totalCost))
    averageCost = totalCost / dvdCount
    print ("Average cost: " + str(averageCost))

def AddDVD():
    name = input("Name: ")
    cost = input("Cost: ")
    InvalidValue = True
    while InvalidValue:
        listValidDVDTypes()
        chosen = input("Enter a number for a dvd type: ")
        if (chosen == "1"):
            type = DVDType.Game
            InvalidValue = False
        if (chosen == "2"):
            type = DVDType.Word
            InvalidValue = False
        if (chosen == "3"):
            type = DVDType.Compiler
            InvalidValue = False
        if (chosen == "4"):
            type = DVDType.Spreadsheet
            InvalidValue = False
        if (chosen == "5"):
            type = DVDType.Dbase
            InvalidValue = False
        if (chosen == "6"):
            type = DVDType.Presentation
            InvalidValue = False

    tree.append(DVD(name, type, cost))


main()

 

 

I tried viewing & reviewing code as I solved a previous bug in this program by reviewing code myself. I tried googling. I tried using my school's learning centre for them to tell me the best way to use the tutor centre is to not use the tutor centre & I even joined the Python Discord to ask & they either didn't want to help or couldn't. As per most of my questions I really do try as much as I can to solve it on my own & end up deleting hour long writing of a thread before I find the problem in 1 second but this time I really cannot figure it out.

You are my only hope.

 

I love you.

Link to comment
Share on other sites

Link to post
Share on other sites

Your FindNode function on line 105 is comparing number to the method GetNumber. You need to call it!

def FindNode(number):
    for val in tree:
        if (number == val.GetNumber):
            return val

should be

def FindNode(number):
    for val in tree:
        if (number == val.GetNumber()):
            return val

 

Link to comment
Share on other sites

Link to post
Share on other sites

19 minutes ago, Garry Motorway said:

Your FindNode function on line 105 is comparing number to the method GetNumber. You need to call it!


def FindNode(number):
    for val in tree:
        if (number == val.GetNumber):
            return val

should be


def FindNode(number):
    for val in tree:
        if (number == val.GetNumber()):
            return val

 

Your first post is the best post ever.

 

Thank you so much! PyCharm didn't tell me this & I have no idea why. Thank you thank you!

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×