# Matt Boutell # This program gives you practice on some key concepts # (types, lists, and strings) during Session 4. from time import clock # Returns a sum of numbers, e.g. sumFrom(3, 5) returns # 3 + 4 + 5 + 6 + 7 def sumFrom(startAt, numberOfTerms): sum = 0 for k in range(startAt, startAt + numberOfTerms): sum += k return sum # Returns n! for the given n def factorial(n): fact = float(1.0) for i in range(2, n + 1): fact *= i return fact # Returns the sum of 1/i for i from 1 to the given number of terms def harmonicSeriesApproximation(nTerms): sum = 0 for i in range(1, nTerms + 1): sum = sum + 1 / i return sum def practiceWithRunTimes(): for k in range(1, 20): # Sum 50,000 int's t1 = clock() sumFrom(k, 50000) t2 = clock() - t1 # Sum 50,000 long's t3 = clock() sumFrom(k + 3000000000, 50000) t4 = clock() - t3 # Sum 50,000 float's t5 = clock() sumFrom(float(k), 50000) t6 = clock() - t5 print k, t2, t4, t6 def practiceNumberTypes(): # TODO: Run the factorial function first to see what it does for n = 10 and n = 1000. # Then modify the function to use integers only and re-test it. n = input("Please enter an integer for the factorial function: ") print "The factorial, using floats, of", n, "is", factorial(n) # TODO: Run the harmonicSeriesApproximation function first to see what it does for n = 10 and n = 1000. # Then modify the function to make it work and re-test it. n = input("Please enter the number of terms of the harmonic series you want: ") print "The sum of the first ", n, "terms is", harmonicSeriesApproximation(n) def practiceWithLists(): # TODO: Print each item in the list on a separate line # Do this twice: once with a range statement and once without one days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] def practiceWithStrings(): # TODO: Print each letter of the quote on a separate line. # Again, do this twice: once with a range statement, and once without a range statement. # TODO: Then write a triple-quoted doc-comment for this function and after # you've run the program again, type "help(practiceWithStrings) to see it!" franklinQuote = 'Who is rich? He who is content. Who is content? Nobody.' def practiceWithStringsInsideLists(): # TODO: Get rid of the annoying hyphens in this quote. While replace works, # try this with split() and join() to get some practice. franklinQuote = 'Who-is-rich?-He-who-is-content.-Who-is-content?-Nobody.' def main(): #TODO: Finish the instructions within a function then test the code by calling the function practiceWithRunTimes() #practiceNumberTypes() #practiceWithLists() #practiceWithStrings() #practiceWithStringsInsideLists() main()