user10186856
user10186856

Reputation:

Check if they are same

I want to read from text file and print the first three words having the same initial three letters. I can get the first 3 initials but I cannot check if they are same or not.

Here is my code:

def main():
  f = open("words.txt", "r+")

  # The loop that prints the initial letters
  for word in f.read().split():
     # the part that takes the 3 initials letters of the word
      initials = [j[:3] for j in word.split()]

      print(initials)

words.txt

when, where, loop, stack, wheel, wheeler 

output

Upvotes: 1

Views: 112

Answers (4)

Eugene Yarmash
Eugene Yarmash

Reputation: 149823

You can use a mapping from the first 3 letters to the list of words. collections.defaultdict could save you a few keystrokes here:

from collections import defaultdict

def get_words():
    d = defaultdict(list)
    with open('words.txt') as f:            
        for line in f:
            for word in line.split(', '):
                prefix = word[:3]
                d[prefix].append(word)
                if len(d[prefix]) == 3:
                    return d[prefix]
    return []

print(get_words())  # ['when', 'where', 'wheel']

Upvotes: 3

gherkin
gherkin

Reputation: 506

def main():
  f = open("words.txt", "r+")

for word in f.read().split():
    record[word[:3]] = record.get(word[:3], [])+[word]
    if len(record[word[:3]]) == 3:
        print (record[word[:3]])
        break 

Upvotes: 0

mad_
mad_

Reputation: 8273

You can use dictionary here with first 3 characters as key. Example

d={}
f = open("words.txt", "r+")
key_with_three_element=''

for word in f.read().split():
 if word[:3] in d:
    d[word[:3]].append(word)
else:
    d[word[:3]]=[word]
if(len(d[word[:3]])==3):
    key_with_three_element=word[:3]
    break
print(d[key_with_three_element])

Ouput:

['when', 'where', 'wheel']

Upvotes: 0

Ralf
Ralf

Reputation: 16505

This code snippet groups the words by there first 3 letters:

def main():
    # a dict where the first 3 letters are the keys and the
    # values are lists of words
    my_dict = {}

    with open("words.txt", "r") as f:
        for line in f:
            for word in line.strip().split():
                s = word[:3]

                if s not in my_dict:
                    # add 3 letters as the key
                    my_dict[s] = []
                my_dict[s].append(word)

                if len(my_dict[s]) == 3:
                    print(my_dict[s])
                    return

    # this will only print if there are no 3 words with the same start letters
    print(my_dict)

This stops the processing (I used a return statement) if you get to 3 words with the same 3 letters.

Upvotes: 0

Related Questions