Simple python program, not easy for me
I need to write a program with four different variants of play words.
One option is for the user to enter a specific word length from a dictionary file, and then the program finds a word that is as long as the abbreviations for the 50 US states.
Ex: If the user enters 6, the program finds the word MARINE, which has 5 abbreviations: MA (Massachusetts), AR (Arizona), RI (Rhode Island), IN (Indiana), and NE (Nebraska).
I have this so far:
elif choice == "d": #wordlen = length of words user is looking for. wordlen = raw_input("Enter the length of words you are looking for: ") wordlen = int(wordlen) print wordlen states = ['AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI',\ 'ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT',\ 'NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD',\ 'TN','TX','UT','VT','VA','WA','WV','WI','WY'] for line in file: line = line.strip() line = line.upper() if len(line) == wordlen:
I already opened the dictionary file (file = file.open ('dictionary.txt') at the beginning of the whole loop and used file.seek (0) and then when the loop was broken (when the user enters 'q') file.close () so that I don't have to open and close the file during every procedure.
And after I have a condition that the user enters data, I don't know what to do. I've tried everything and it doesn't give me the expected result. Please help me? This is my first year doing python and it confuses me a lot -__-
source to share
For every line in the dictionary file that is the correct length (for example, the length of the user's input), you need to check every consecutive pair of letters in that word to see if it shows up in the list of states.
for line in file: line = line.strip() line = line.upper() if len(line) == wordlen: # Set some counters/containers. pair_is_abbrev = 1 #<-- Marks true/false if pair is in abbrev list. cur_letter_indx = 0 #<-- Counts the location we're at in this line. # Loop until we find a two-letter sequence that not an abbrev. # or until we hit the end of this line (the word length). while(pair_is_abbrev and cur_letter_indx <= wordlen-1): cur_pair = line[cur_letter_indx:(cur_letter_indx+2)] #<-- Get current two letters pair_is_abbrev = (cur_pair in states) #<-- Python way to check if that pair is in your list of abbrevs. cur_letter_indx = cur_letter_indx + 1 #<-- Increment the counter. # Once the loop terminates, pair_is_abbrev can only be true if we # made it all the way to the end of the line successfully. If so, # then we found an all-abbrevs word. Otherwise, move on to the next line. if(pair_is_abbrev): print "Found a word made of abbreviations that is the right length:" print line
source to share