Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!