# Answers to Lists and String Exercises # 1a. ======================================================== def LFindWhile(someList,someElement): i = 0 while i < len(someList): if someList[i] == someElement: return i i += 1 return -1 # print LFindWhile([3, 4, "hi", -2], "hi") # print LFindWhile([3, 4, "hi", -2], "HI") # 1b. ======================================================== def LFindNoWhile(someList,someElement): if someElement in someList: return someList.index(someElement) return -1 # print LFindNoWhile([3, 4, "hi", -2], "hi") # print LFindNoWhile([3, 4, "hi", -2], "HI") # 2. ========================================================== def CountSomeChars(s): littleHalf = "abcdefghijklm" half = littleHalf + littleHalf.upper() count = 0 for c in s: if c in half: count += 1 return count # print CountSomeChars('Hi there') # 3. ============================================================= def HarmonicSum(n): total = 0 for i in range(1,1001): total += 1.0/i return total # print '%.3f' % HarmonicSum(1000) # There are special, built-in number formatting commands that we can make use # of (though not covered in class) # To find out, go to the usual French Python page: # http://rgruet.free.fr/PQR27/PQR2.7.html # and search for "string formatting with the % operator" # 4. ============================================================== def Select23(someList): result = [] for n in someList: if n%2 == 0 or n%3 == 0: result.append(n) return result # print Select23([5,0,12,9,7,4]) # print Select23([5,7,1]) # 5a. ============================================================= def RemoveNegs(L): result = [] for n in L: if n >= 0: result.append(n) return result # L = [2, -3, 0, -5, 12] # print RemoveNegs(L) # print L # 5b. ============================================================= def RemoveNegsInPlace(L): i = 0 while i < len(L): if L[i] < 0: del L[i] else: i += 1 # L = [2, -3, 0, -5, 12] # print RemoveNegsInPlace(L) # print L # Challenge ========================================================= def WordList(someString): # remove all commas and periods someString = someString.replace(',','') someString = someString.replace('.','') return someString.split() # print WordList(' Now, Scotty, use the dilithium crystals.') # Hard Challenge ==================================================== def MySplit(someString,separators): insideWord = False words = [] currentWord = '' for c in someString: if c in separators: if insideWord: words.append(currentWord) currentWord = '' insideWord = False else: insideWord = True currentWord += c # if there's still a currentWord building up... if insideWord: words.append(currentWord) return words # print MySplit(" Hi there... Mr. Bleeper, "," ,.e") # print MySplit("What's up?"," ,!")