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

Davis Rousseau
Davis Rousseau
6,670 Points

Not sure how to begin

Implement function duplicate() that takes as input a string and the name of a file in hte current directory and returns True if the files contains duplicate words and False otherwise.

duplicate('Duplicates.txt') True

duplicate('noDuplicates.txt') False

What I have so far

def duplicate(filename):

Ken Alger
Ken Alger
Treehouse Teacher

Davis;

Would you mind referencing the challenge on which you are working?

Thanks,

Ken

4 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Let me introduce you to set(). A set is a like a list but it can only contain unique members. You can make a set with set(<list>).

So take all of the words in the file into a list. Then make a set of that list. If they have different len()s, there are some duplicated words.

Ben Fishbein
Ben Fishbein
10,228 Points

Many ways to do it. Here's one:

def duplicate(text):

words = text.split()

words2 = []

for word in words:

    if word in words2:

        return True

    else:

        words2.append(word)

return False
Ben Fishbein
Ben Fishbein
10,228 Points

def duplicate(text):

words = text.split()

for word in words:

    if text.count(word) > 1:

        return True

return False
Davis Rousseau
Davis Rousseau
6,670 Points

It's not a challenge sorry!