one-file-projects/decisiontree.py
2014-09-12 17:12:02 +02:00

66 lines
1.7 KiB
Python

class Node(object):
pass
def menu(prompt, decisions):
print("> %s" % prompt)
for i,decision in enumerate(decisions):
print("%d. %s" % (i,decision))
answer = int(input("Answer: "))
return answer
class DecisionNode(Node):
def __init__(self, question):
self.question = question
self.decisions = []
def addDecision(self, response, node):
self.decisions.append( (response,node) )
def display(self):
i = menu(self.question, [ d[0] for d in self.decisions ])
return self.decisions[i][1]
class AnswerNode(Node):
def __init__(self, answer):
self.answer = answer
def display(self):
print(self.answer)
return None
if __name__ == "__main__":
high = AnswerNode("hohes Risiko")
medium = AnswerNode("mittleres Risiko")
low = AnswerNode("niedriges Risiko")
n6 = DecisionNode("Einkommen?")
n6.addDecision("0 Eur bis 15 Tsd Eur", high)
n6.addDecision("15 Tsd Eur bis 35 Tsd Eur", medium)
n6.addDecision("ueber 35 Tsd Eur", low)
n4 = DecisionNode("Sicherheiten?")
n4.addDecision("keine", n6)
n4.addDecision("angemessen", low)
n3 = DecisionNode("Verschuldung?")
n3.addDecision("hoch", n4)
n3.addDecision("niedrig", low)
n2 = DecisionNode("Sicherheiten?")
n2.addDecision("keine", high)
n2.addDecision("angemessen", medium)
n1 = DecisionNode("Verschuldung?")
n1.addDecision("hoch", high)
n1.addDecision("niedrig", n4)
n0 = DecisionNode("Kreditwuerdigkeit?")
n0.addDecision("unbekannt",n1)
n0.addDecision("schlecht",n2)
n0.addDecision("gut",n3)
node = n0
while node is not None:
node = node.display()