(Solved) : Trietesterpy Class Mytrie Def Init Self Initialize Trie Node Needed Pass Def Insert Self W Q42762906 . . .

Python Topics: Tries, recursion Summary: Given: You are given a Python Class template, and a list of words in the file ameri

trietester.py

class MyTrie:
    def __init__(self):
        # Initialize the trienode as needed
        pass
  
    def insert(self, word):
        # Insert a word intothis trie node
        pass

    def exists(self, word, position=0):
        # Return true if thepassed word exists in this trie node
        # A terminal node willreturn true if the word passed is “”
        pass

    def isTerminal(self):
        # Return true if thisnode is the terminal point of a word
        pass

    def autoComplete(self, prefix,position=0):
        # Return every word thatextends this prefix in alphabetical order
        pass

    def __len__(self):
        # Return the number ofwords that either terminate at this node or descend from thisnode
        # A terminal leaf shouldhave length 1, the node A with terminal child leaves B|C shouldhave length 2
        pass

#trietester.py

#   You will need the ‘american-english-no-accents’file in the directory of the tester

import random
import string
import re
#Module Imports
import string
import sys
from importlib import import_module

wordlist = []

def GenerateWord(size):
    chars=string.ascii_letters+”‘”
    word=””
    for i in range(0, random.randint(size/2,size)):
        word +=random.choice(chars)
    return word

def Test(lib, seed=0, size=10, rounds=10, verbose=False,wordlist=[]):

    if not lib:
        print(“You need toinclude a testable library”)
        return False

    if not wordlist:
        f =open(“american-english-no-accents.txt”, “r”)
        readwords =f.readlines()
        for word inreadwords:
           wordlist.append(word)

    random.seed(a=seed)

    trie = lib.MyTrie()

    for word in wordlist:
        trie.insert(word)

    if len(wordlist) != len(trie):
        if verbose:
           print(“Trie size mismatch!”)
        return False

    if verbose:
        print(“Insertion testcomplete”)
    yield True

    for j in range(0, rounds):
        expected = True
        c=””

        ifrandom.randint(0,2) == 0:
           c = GenerateWord(6)
        else:
           c = wordlist[random.randint(0, len(wordlist))]
        expected = c inwordlist
        res =trie.exists(c)
        if res !=expected:
           if verbose:
               print(“Word ” + c + ” was ” + (“found” if res else “not found”) + “and was expected to ” + (“” if expected else “not”) + ” be.”)
           return False
    if verbose:
        print(“Trie item testcomplete”)
    yield True

    try:
        mlist =trie.autoComplete(“”)
    except:
        if verbose:
           print(“Error: Autocomplete method not callble”)
        return False

    if not(mlist == wordlist):
        if verbose:
           print(“Error: Autocomplete missing items for empty list”)
        return False
  
    if verbose:
        print(“Completeretrieval test complete”)
    yield True

    try:
        emptyList =trie.autoComplete(“fasdfasdfasdfasfawef”)
    except:
        if verbose:
           print(“Error: Autocomplete does not respond to unmatchedprefix”)
        return False
  
    if len(emptyList) != 0:
        if verbose:
           print(“Error: Autocomplete returning items for unmatchableprefix”)
        return False

    if verbose:
        print(“Unmatchableprefix test complete”)
    yield True

    for j in range(0,rounds):
        w = “”
        while len(w) <4:
           w = random.choice(wordlist)
        prefix = w[0:3]

        matchlist =list(filter(lambda x: x.startswith(prefix), wordlist))
        try:
           autocompletelist = trie.autoComplete(prefix)
        except:
           if verbose:
               print(“Error: Autocomplete method not callable”)
           return False
      
        if not (matchlist ==autocompletelist): # Check more problems? ie not in order, in orderbut missing, etc
           print(matchlist)
           print()
           print()
           print(autocompletelist)
           if verbose:
               print(“Error: Autocomplete method not returning correctinformation”)
           return False

    if verbose:
        print(“Autocomplete testcomplete”)
    yield True

if __name__ == “__main__”:
    try:
        f =open(“american-english-no-accents.txt”, “r”)
    except:
        print(“Error: Pleaseensure the wordlist file is in this directory.”)
        exit()
    readwords = f.readlines()
    for word in readwords:
       wordlist.append(word.rstrip())

    if len(sys.argv) < 2:
        print(“Include at leasta library name as an argument.”)
        exit()
    name = sys.argv[1]
    if name.endswith(“.py”):
        name = name[:-3]
    print(f”Testing module {name}”)
   module=import_module(name,package=__name__)
    score=0
    for i in Test(module,seed=123456, size=20,verbose=True, wordlist = wordlist):
        if i:
           score+=1
        else:
           break
    print(f”Test result: {score}/5″)

american-english-no-accents.txt

A
A’s
AA’s
AB’s
ABM’s
AC’s
ACTH’s
AI’s
AIDS’s
AM’s
AOL
AOL’s
ASCII’s
ASL’s
ATM’s
ATP’s
AWOL’s
AZ’s
AZT’s
Aachen
Aaliyah
Aaliyah’s
Aaron
Abbas
Abbasid
Abbott
Abbott’s
Abby
Abby’s
Abdul
Abdul’s
Abe
Abe’s
Abel
Abel’s
Abelard
Abelson
Abelson’s
Aberdeen
Aberdeen’s
Abernathy
Abernathy’s
Abidjan
Abidjan’s
Abigail
Abilene
Abner
Abner’s
Abraham
Abraham’s
Abram
Abram’s
Abrams
Absalom
Abuja
Abyssinia
Abyssinia’s
Abyssinian
Abyssinian’s
Ac
Ac’s
Acadia
Acadia’s
Acapulco
Acapulco’s
Accenture
Accenture’s
Accra
Accra’s
Acevedo
Acevedo’s
Achaean
Achaean’s
Achebe
Achebe’s
Achernar
Acheson
Acheson’s
Achilles
Achilles’s
Aconcagua
Aconcagua’s
Acosta
Acosta’s
Acropolis
Acrux
Acrux’s
Actaeon
Acton
Acts
Acuff
Acuff’s
Ada
Ada’s
Adam
Adam’s
Adams
Adan
Adan’s
Adana

Python Topics: Tries, recursion Summary: Given: You are given a Python Class template, and a list of words in the file ‘american.-english.-no-accents. txt’. In the template Task: Write a recursive trie data structure. Each node should store either a character or a word. Then, implement the autocomplete method. This method shou ld recursively explore the trie and return a list of all words in the trie that match that prefix. The list must be in alphabetical order. Example Given the wo rds ‘dad’, ‘daddy’, ‘daddio’, ‘danny’, and ‘mummy’, the trie should look like this: mum’ d Im a d m dad danny / mum / daddy daddio mummy When the prefix ‘da’ is autocompleted, the list returned should be [‘dad’, ‘daddio’, ‘daddy’, ‘danny’]. When the prefix ” is given, every word in the trie should be returned, in alphabetical order. When the prefix ‘uncl’ is given, an empty list should be returned Notes : Ensure that duplicate words do not get added to the trie twice. Both lower and upper case letters will be used. Consider them as seperate characters, upper case letters coming before lower case. The file ‘american.-english.-no.-ascents.. txt’ is used by the tester but you can write your own test dictionary and tester program Show transcribed image text Python Topics: Tries, recursion Summary: Given: You are given a Python Class template, and a list of words in the file ‘american.-english.-no-accents. txt’. In the template Task: Write a recursive trie data structure. Each node should store either a character or a word. Then, implement the autocomplete method. This method shou ld recursively explore the trie and return a list of all words in the trie that match that prefix. The list must be in alphabetical order. Example Given the wo rds ‘dad’, ‘daddy’, ‘daddio’, ‘danny’, and ‘mummy’, the trie should look like this: mum’ d Im a d m dad danny / mum / daddy daddio mummy When the prefix ‘da’ is autocompleted, the list returned should be [‘dad’, ‘daddio’, ‘daddy’, ‘danny’]. When the prefix ” is given, every word in the trie should be returned, in alphabetical order. When the prefix ‘uncl’ is given, an empty list should be returned Notes : Ensure that duplicate words do not get added to the trie twice. Both lower and upper case letters will be used. Consider them as seperate characters, upper case letters coming before lower case. The file ‘american.-english.-no.-ascents.. txt’ is used by the tester but you can write your own test dictionary and tester program

Expert Answer


Answer to trietester.py class MyTrie: def __init__(self): # Initialize the trie node as needed pass def insert(self, word): # Inse…

Leave a Comment

About

We are the best freelance writing portal. Looking for online writing, editing or proofreading jobs? We have plenty of writing assignments to handle.

Quick Links

Browse Solutions

Place Order

About Us