Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python program Define the functions near1 and near2, which take two arguments: a

ID: 649681 • Letter: P

Question

Python program

Define the functions near1 and near2, which take two arguments: a str that is one word and an int; each returns a dictionary whose keys are every letter in the word, and whose associated values are a set of those letters that are near the key (note that the same key might occur in different parts of the word), where nearness means the distance between the letter indexes is <= the int argument. Hint: use one loop and string slices (where one part of the slice uses the max function).

Forexample near1('whiplash

Explanation / Answer

def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]

def near1(s,n):
   dict = {}
   for char in s:
       if (dict.has_key(char) == False):
           dict[char] = []
           l = find(s,char)
           for num in l:
               i = 0
               while (True):
                   if (num - i >= 0):
                       if (s[num-i] not in dict[char]):
                           dict[char].append(s[num-i])
                   if (num + i <= len(s)-1):
                       if (s[num+i] not in dict[char]):
                           dict[char].append(s[num+i])
                   i += 1
                   if (i > n):
                       break
return dict

def near2(s,n):
   dict = {}
   for char in s:
       if (dict.has_key(char) == False):
           dict[char] = []
           l = find(s,char)
           for num in l:
               i = 0
               while (True):
                   if (num - i >= 0):
                       if (s[num-i] not in dict[char]):
                           dict[char].append(s[num-i])
                   if (num + i <= len(s)-1):
                       if (s[num+i] not in dict[char]):
                           dict[char].append(s[num+i])
                   i += 1
                   if (i > n):
                       break
   print dict
   pass

d = near1('whiplash',2);