The Python Game Book

code games. learn Python.

User Tools

Site Tools


Sidebar

Github:

en:glossary:l:linked_list

linked list

A data structure where each element has a pointer to the next element. Liked lists have advantages and disadvantages over other data structures such as arrays. See:

Python example for a linked list (using class) to create an animal-guess game:

#
#  A n i m a l . p y
# derived from http://www.openbookproject.net/py4fun/animal/animal.html
# linked list

class Node:
    
    """Node objects have a question, and  left and right pointer to other Nodes"""
    def __init__ (self, question, left=None, right=None) :
        self.question = question
        self.left     = left   
        self.right    = right  
        
    def __str__(self):
        return self.question

def is_yes(ques):
    "The user answers 'yes' or something similar. Otherwise it's a no"
    ans = input(ques)
    if ans[0].lower() == 'y' :
             return True
    return False


def print_tree(start_node):
    """rercursive print all nodes"""
    print(start_node.question, start_node.left, start_node.right)
    if start_node.left is not None:
        print_tree(start_node.left)
    if start_node.right is not None:
        print_tree(start_node.right)

knowledge = Node("bird")

def main () :
    "Guess the animal. Add a new Node for a wrong guess."

    while True :
        print("my knowledge:")
        print_tree(knowledge)
        if not is_yes("Are you thinking of an animal? "):
            break
        p = knowledge
        while p.left != None :
            if is_yes(p.question+"? "):
                p = p.right
            else: 
                p = p.left
    
        if is_yes("Is it a " + p.question + "? ") :
             continue
        animal   = input("What is the animals name? ")
        text = "What question would distinguish a {} from a {}?".format(
               animal, p.question)
        question = input(text)
        p.left     = Node(p.question)
        p.right    = Node(animal)
        p.question = question
    
        if not is_yes("If the animal were a {} the answer would be? ".format(
            animal)):
            (p.right, p.left) = (p.left, p.right)

if __name__ == "__main__" : 
    main()

en/glossary/l/linked_list.txt · Last modified: 2020/06/01 05:29 by horst