Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Search Engine with Python

Hi there. I was doing some extra exercise apart from the treehouse track and I got this one. Given an ORDERED (ascendent order) list of tuples (pairs) where the first element is a word in a file and the second is the name of the file itself, the search engine should check for possible similar words between different files and at the end print a list with all the words coupled with the name of the file they belong. For instance, starting with a similar list ordered according to the word:

x = [['boat', 'a.txt'], ['boat', 'c.txt'], ['cat', 'b.txt'], ['dog', 'a.txt'], ['dog', 'b.txt'], ['dog', 'c.txt'], ['house', 'a.txt'], ['rat', 'c.txt']]

my output should be:

res = [['boat', ['a.txt', 'c.txt']], ['cat', ['b.txt']], ['dog', ['a.txt', 'b.txt', 'c.txt']], ['house', ['a.txt']], ['rat', ['c.txt']] 

I tried different ways without success. I am posting one of the versions I did. In this one, I am trying to separate the words and file name into two separate lists to append simultaneously to the res list. Unfortunately, I get an index error. I tried some fixing but I couldn't make it work.... I need some help, please

def make_table(pairs):
    res = []
    fresh = fpairs[0]
    i = 1
    k = 0
    while i < len(fpairs):

        if fpairs[i][0] != fresh:
            res[k][0].append(fresh[0])
            res[k][1].append(fresh[1])
            fresh = fpairs[i]
            k += 1
        else:
            res[k][1].append(fresh[1])
        i += 1

    res.append([word, file])

x = [['boat', 'a.txt'], ['boat', 'c.txt'], ['cat', 'b.txt'], ['dog', 'a.txt'], ['dog', 'b.txt'], ['dog', 'c.txt'], ['house', 'a.txt'], ['rat', 'c.txt']]
make_table(x)
def make_table(pairs):
    res = []
    fresh = fpairs[0]
    i = 1
    k = 0
    while i < len(fpairs):
        print(fresh)
        print(fresh[0])
        if fpairs[i][0] != fresh:
            res[k][0].append(fresh[0])
            res[k][1].append(fresh[1])
            fresh = fpairs[i]
            k += 1
        else:
            res[k][1].append(fresh[1])
            print(file)
        i += 1
    res.append([word, file])

[MOD: Added ```python formatting -cf]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

When running your code, I get the error:

NameError: name 'fpairs' is not defined