# 1a. def SFind(some_string,c): ''' Return the first position that c occurs in some_string, else -1 ''' i=0 while i < len(some_string): if some_string[i] == c: return i i=i+1 return -1 # 1b. def SRFind(some_string,c): '''Return the last position where c occurs in some_string, else -1 ''' i=len(some_string)-1 while i >= 0: if some_string[i] == c: return i i=i-1 return -1 # 2a. def Convert(s,before,after): '''Translate the chars in s, using the "before" alphabet converting to the "after" alphabet''' answer='' i=0 while i < len(s): pos=SFind(before,s[i]) if pos>=0: answer=answer+after[pos] else: answer=answer+s[i] i=i+1 return answer def ToUpper(s): lowers='abcdefghijklmnopqrstuvwxyz' uppers='ABCDEFGHIJKLMNOPQRSTUVWXYZ' return Convert(s,lowers,uppers) # 2b. def Encrypt(s): Julius_before='defghijklmnopqrstuvwxyzabcDEFGHIJKLMNOPQRSTUVWXYZABC' Julius_after ='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' return Convert(s,Julius_before,Julius_after) def Decrypt(s): Julius_before='defghijklmnopqrstuvwxyzabcDEFGHIJKLMNOPQRSTUVWXYZABC' Julius_after ='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' return Convert(s,Julius_after,Julius_before) # 3a. def FirstLast(name): '''converts "lastname, firstname" to "firstname lastname" ''' pos=SFind(name,',') return name[pos+2:]+' '+name[:pos] # 3b. def FirstLastSequence(names): ''' converts a sequence of "lastname, firstname" pairs terminated by ";" to "firstname lastname" pairs also terminated by ";" ''' end_of_pair = SFind(names,';') answer = '' while end_of_pair != -1: just_the_first_pair = names[:end_of_pair] the_rest = names[end_of_pair+1:] answer = answer + FirstLast(just_the_first_pair) + ';' names = the_rest end_of_pair = SFind(names,';') return answer # 4. def FileClassifier(filename): ''' Classifies filenames according to content recognized by the suffix''' pos = SRFind(filename,'.') suffix = ToUpper(filename[pos+1:]) if suffix == 'JPG' or suffix == 'JPEG': return 'picture' if suffix == 'MP3': return 'music' if suffix == 'NLOGO': return 'Netlogo' if suffix == 'PY': return 'Python' return 'Unrecognized'