# String exercises answers # 1a ====================================================== def ToUpper(s): alpha_lower='abcdefghijklmnopqrstuvwxyz' alpha_upper='ABCDEFGHIJKLMNOPQRSTUVWXYZ' c=0 answer='' while c < len(s): ch=s[c] pos=alpha_lower.find(ch) if pos >= 0: answer += alpha_upper[pos] else: answer += ch c += 1 return answer # 1b ========================================================== Julius_before='defghijklmnopqrstuvwxyzabcDEFGHIJKLMNOPQRSTUVWXYZABC' Julius_after ='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' def Encrypt(some_text): return Crypt(some_text, Julius_before, Julius_after) def Decrypt(encrypted_text): return Crypt(encrypted_text, Julius_after, Julius_before) def Crypt(the_text, alpha_from, alpha_to): c=0 answer='' while c < len(the_text): ch=the_text[c] pos=alpha_from.find(ch) if pos >= 0: answer += alpha_to[pos] else: answer += ch c += 1 return answer # 2a =========================================================== def IsSameName(name1,name2): return name1.upper() == name2.upper() # 2b =========================================================== def CapWord(word): return word[0].upper() + word[1:].lower() # 2c ============================================================ def CapName(name): pos=name.find(' ') return CapWord(name[:pos+1]) + CapWord(name[pos+1:]) # 3a ============================================================= def FirstLast(name): pos=name.find(',') return name[pos+2:] + ' ' + name[:pos] # 3b ============================================================= def FirstLastSequence(names): answer='' while names != '': pos = names.find(';') answer += FirstLast(names[:pos]) + ';' names = names[pos+1:] return answer # 4 ============================================================== def FileClassifier(filename): fname=filename.lower() if fname.endswith('.jpg') or fname.endswith('.jpeg'): return 'picture' if fname.endswith('.mp3'): return 'music' if fname.endswith('.nlogo'): return 'Netlogo' if fname.endswith('.py'): return 'Python' return 'Huh?' # Triple Challenge ================================================== alphabet='abcdefghijklmnopqrstuvwxyz' crypt_text='Zw Z yrmv jvve wlikyvi zk zj sp jkreuzex fe kyv jyfcuvij fw Xzrekj.' teams='JETS;NETS;KNICKS;GIANTS;RANGERS;YANKEES;METS;ISLANDERS;' def Triple(): shift=1 alpha_from = alphabet + alphabet.upper() while shift < 26: alpha_to = ShiftAlpha(alphabet, shift) trial_text = Crypt(crypt_text, alpha_from, alpha_to) if CheckTeams(trial_text, teams): return trial_text shift += 1 return 'Huh?' def ShiftAlpha(s, shift_by): new_alpha = s[shift_by:] + s[:shift_by] return new_alpha + new_alpha.upper() def CheckTeams(the_text, the_teams): THE_TEXT = the_text.upper() while the_teams != '': pos = the_teams.find(';') a_team = the_teams[:pos] if THE_TEXT.find(a_team) >= 0: return True the_teams = the_teams[pos+1:] return False