Write a python program: Part1 : Pattern to Word a. for a given string of charact
ID: 3879413 • Letter: W
Question
Write a python program:
Part1 : Pattern to Word
a. for a given string of characters representing a word pattern, return possible candidate words (take advantage of words_aplha.txt and you may want to create a new file)
For example, the pattern "abbcd" will return a list of candidates as:
apple
essay
reefs
hooky
leets
wooly
:
Likewise if a word is entered "apple" then the candidate list is also returned
b. The program should be able to take a string from console (typed word) or read words from a file.
Explanation / Answer
This problem can be solved in many ways and here I am just proposing one of those algorithm. I am first reading a file(input.txt) and store each line to list.Then I am taking pattern as input from User.Here I have also created a function which takes a string and modify it to resulting pattern string.Function works like this that for first distinct it will insert 0 , for second distinct it will insert 1 and same. For example apple will modify to 01123 and abbcd will also modify to 01123.Now for each string of initial list check that if by modifying that string equals to modified pattern or not. Here is the code and if you have any problem understanding any part of code you can write in comments-
def modify(a):
#dictionary to modify a string
dict={}
for j in range(ord('a'),ord('z')+1):
#setting initial value to dictionary
dict[chr(j)]="$"
#creating output string
output=""
#index to iterate over given string
i=0
j=0
while i<len(a):
if dict[a[i]]=="$":
dict[a[i]]=str(j)
j=j+1
output=output+dict[a[i]]
i=i+1
return output
if __name__=='__main__':
#reading a file and storing in list
file=open("input.txt","r")
list=[]
for line in file:
list.append(line)
#taking input Pattern from User
x=str(input("Enter Pattern:"))
pattern=modify(x)
#creating an object to write to file
out=open("output.txt","w")
for s in list:
if modify(s)==pattern:
#writing to file
out.write(s+' ')
#closing the object
f.close()
out.close()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.