Search This Blog

Tuesday, February 25, 2014

Given two words of equal length that are in a dictionary, write a method to transform one word into another word by changing only one letter at a time. The new word you get in each step must be in the dictionary.

__author__ = 'nitin'

import copy

string_1='damp'
string_2='like'
strings_list=['damp','lamp','limp','lime','like','nitin','nitzz']

def convert_word():
    list_1=list(string_1)
    list_2=list(string_2)
    print "\nBefore Conversion list_1 :", "".join(list_1)
    print "Before Conversion list_2 :", "".join(list_2), "\n"
    iter_list=len(list_2)
    i=0
    record_list=[]
    while iter_list>0:
        temp_list=copy.deepcopy(list_1)
        iter_temp=len(temp_list)
        while iter_temp>0:
            temp_list=copy.deepcopy(list_1)
            if i not in record_list:
                temp_list[i]=list_2[i]
                res_str="".join(temp_list)
                if res_str in strings_list:
                    list_1=temp_list
                    record_list.append(i)
                    i=0
                    break
                else:
                    i=i+1
                    iter_temp=iter_temp -1
            else:
                i=i+1
                iter_temp=iter_temp -1
            if i==len(list_1):
                i=0
        iter_list=iter_list -1
    print "After Conversion list_1 :", "".join(list_1)
    print "After Conversion list_2 :", "".join(list_2), "\n"
    if list_1==list_2:
        print "Successfully Converted"
    else:
        print "One of the combination was not present in dictionary"

if __name__=='__main__':
    convert_word()

No comments:

My Profile

My photo
can be reached at 09916017317