0

In Darius Bacon's code, on the line 11 and 12, there is the following code:

prefixes = set(word[:i] for word in words for i in range(2, len(word)+1))

I'm trying to translate his program into Java and I'm having difficulties with this one.

What does this do?

3
  • 4
    why don't you try it with a list of words? Commented Nov 11, 2012 at 17:42
  • So what have you tried? Beyond that, translating code from one language to another is always a terrible idea. It generally means you end up with code that doesn't use the features of the language and behaves weirdly. Take what the code is doing and do it in the language you want to do, rather than trying to translate the code itself. Commented Nov 11, 2012 at 17:58
  • Sorry, I didn't come up with any other word ;) Of course it's not 1:1 with Darius' program and therefore not translating. Commented Nov 11, 2012 at 18:05

2 Answers 2

6

Expanding the list comprehension:

prefixes = set()
for word in words:
    for i in range(2, len(word)+1)
        prefixes.add(word[:i])

word[:i] is word up to but not including index i

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for expaining! This clarified the code and I managed to code it in Java :)
3

Try this in Java

Set<String> prefixes = new HashSet<String>();
for(String word:words){
  for(int i=1;i<word.length;i++){ 
     prefixes.add(word.substring(0,i));
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.