# Answers to the String/List Test on Friday 4/12: # Problem 1 def MyLower(s): answer = '' for c in answer: if ord('A') <= ord(c) <= ord('Z'): answer += chr(ord(c) - ord('A') + ord('a')) else: answer += c return answer def countString(target,lookfor): count = 0 target_low = MyLower(target) lookfor_low = MyLower(lookfor) ln_target = len(target) ln_lookfor = len(lookfor) for i in range(len(target)-len(lookfor)+1): if target_low[i:i+ln_lookfor] == lookfor_low: count += 1 return count # Problem 2 def IsInteger(word): if len(word) == 0: return False if word[0] == '-' or word[0] == '+': word = word[1:] return word.isdigit() def addIntegers(s): words = s.split(';') answer = 0 for word in words: if IsInteger(word): answer += int(word) return answer # Problem 3 def Eng2Kling(s): # create 2 lists, first of English words and second of Klingon words Eng = [] Kling = [] pairs = KL.split('\n') for pair in pairs: words = pair.split('=') Eng.append(words[0]) Kling.append(words[1]) # now translate s answer = '' PhraseWords = s.split() for word in PhraseWords: # now, let's find the position of the English word in the English list # Way #1: pos = Eng.index(word) # or Way #2: for pos in range(len(Eng)): if Eng[pos] == word: break # or Way #3: pos = 0 while Eng[pos] != word: pos += 1 KlingWord = Kling[pos] answer += KlingWord + ' ' return answer[:-1] # Problem 4 def Interleave(A,B): answer = [] for i in range(len(A)): answer.append(A[i]) if len(B) > i: answer.append(B[i]) else: # no more B's, so add all the leftover A's answer += A[i+1:] return answer # add any leftover B's answer += B[len(A):] return answer # Problem 5 def countStringRecursive(target, lookfor): if len(target) < len(lookfor): return 0 my_answer = 0 if target[:len(lookfor)] == lookfor: my_answer = 1 return my_answer + countStringRecursive(target[1:],lookfor)