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?

Community
  • 1
  • 1
MikkoP
  • 4,864
  • 16
  • 58
  • 106
  • 4
    why don't you try it with a list of words? – mata Nov 11 '12 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. – Gareth Latty Nov 11 '12 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. – MikkoP Nov 11 '12 at 18:05

2 Answers2

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

Eric
  • 95,302
  • 53
  • 242
  • 374
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));
  }
}
Ankur
  • 12,676
  • 7
  • 37
  • 67