******* Find the average length of all strings in a list of strings ["apple", "bear", "cat", "friends"] 5 + 4 + 3 + 6 = 18/4 = 4.5 def avg(words): tot = 0 for x in words: tot = tot + len(x) return 1.0*tot/len(words) def avg(words): return 1.0*sum([len(x) for x in words])/len(words) ******* Is a number prime? Prime numbers are only divisible by one and themselves, 49 isn't prime (divisible by 7), 53 is prime def is_prime(n): for div in range(2,n): if n % div == 0: return False return True ******** Read a file and return a list of all words with more than three vowels def v3(fname): f = open(fname) str = f.read() ret = [] for word in str.split(): if lotsvowels(word): ret.append(word) return ret --- write lotsvowels: def lotsvowels(word): tot = 0 for let in word: if "aeiou".find(let) >= 0: tot = tot + 1 return tot > 3 ******** find the longest runof H's in a string of H,T longh("HHHTTTHHHHHTTHHHHHHTTTTHH") is 6 def longh(st): best = 0 run = 0 for ch in st: if ch == 'H': run = run + 1 if run > best: best = run else: run = 0 return best ******** create acronym from last letter in a list of string ["this", "pony", "cub", "luna", "car", "radii", "cat", "bee"] produces: "sybarite" def lastac(words): w = "" for word in words: w = w + word[-1] return w ********* Read a file, count how many times each word in the file occurs using a dictionary, return a list of words sorted by frequency def words(fname): f = open(fname) d = {} for line in f: parts = line.strip().split() # list of words for word in parts: if word not in d: d[word] = 0 d[word] += 1 #d is a dictionary of word/frequency pairs, sort by frequency: ret = sorted(d.items(), key=operator.itemgetter(1)) return ret ************ compute the words in common to two lists a and b a = ['apple', 'bear', 'cherry, 'lion'] b = ['bear', 'lion', 'tiger', 'giraffe'] common = list(set(a) & set(b)) # common = ['bear', 'lion'] combo = list(set(a) | set(b)) # combo = ['apple', 'bear', 'cherry, 'lion', 'tiger', 'giraffe'] ************ store words in a file and a list of line numbers on which words occur, list is sorted with each line number occuring once def words(fname): f = open(fname) d = {} line_num = 0 for line in f: parts = line.strip().split() # list of words line_num += 1 for word in parts: if word not in d: d[word] = set() d[word].add(line_num) for key in d: d[key] = sorted(d[key]) return d