Phone Tree

Denis McMahon denismfmcmahon at gmail.com
Mon Sep 14 01:57:50 CEST 2015


On Sun, 13 Sep 2015 07:39:23 -0700, Azureaus wrote:

> Does anyone have any ideas for a more elegant solution? My thoughts are
> that I could use a tree data structure and hence make traversing the
> tree recursive based on yes or no answers. I'm happy to put the time in
> to explain these more complex ideas, I'm just hoping those with more
> expertise than myself could either help verify the idea or suggest
> alternatives.

The trick is to separate the data and the processing.

Each question has a yes, no answer, so start with a dictionary of data 
tuples (you could use a list, but using a dictionary makes the 
relationship slightly easier to walk through):

questions = {
1: (q1, response if yes, response if no),
2: (q2, response if yes, response if no) .... }

The responses can be either a number of another question, or a result 
text.

Then your algorithm is broadly:

x = 1:
while x is numeric:
    ask questions[x][0]
    if answer is "yes":
        x = questions[x][1]
    if answer is "no":
        x = questions[x][2]
answer is x

You can use a list instead of a dictionary, just remember 0 indexing when 
you're working out which question leads to which next question.

This way also makes for an interesting talking point about separating 
data and code, especially given the multiple if statements issue.

-- 
Denis McMahon, denismfmcmahon at gmail.com


More information about the Python-list mailing list