# CS190C: Spring 2009 # Daniel Tang # Problem Set 1, Problem 1 def main(): print 'This program calculates the wind chill, given a temperature in' print 'degrees Fahrenheit and wind speed in miles per hour.' print t = input('Enter the temperature in degrees Fahrenheit: ') v = input('Enter the wind speed in miles per hour: ') # Calculate the wind chill w. This should mostly look like graphing # calculator syntax on the right-hand side of the equals sign. The only # thing new here is using ** as your exponent instead of ^. w = 35.74 + 0.6215*t + (0.4275*t - 35.75)*(v**0.16) print 'For a temperature of', t, 'and wind speed of', v, 'the wind chill is', w, 'degrees Fahrenheit.' main()
# CS190C: Spring 2009 # Daniel Tang # Problem Set 1, Problem 2 def main(): print 'This program evaluates the first n terms of a geometric series.' print # Remember, it's possible to grab input for several variables at once. a, r, n = input('Enter a, r, n (for example "1, 2, 20"): ') # The accumulator variable should start at 0. If not, you have to handle # the case that n = 0 separately. total = 0 # The current_ratio variable will keep track of the value of r^i. This is # cheaper than doing r**i for every iteration of the loop, since it only # requires one multiplication each time. It starts at 1 because r^0 = 1 # regardless of r. current_ratio = 1 # For some reason, many of you put "range(n+1)" or something like it. This # will evaluate n+1 terms instead of n. for i in range(n): # One trick to making this program more efficient is factoring out the # constant a and doing the multiplication after the loop (see below) total += current_ratio # After the below line is processed, current_ratio is r^(i+1). But this # is what we want, since it is the r^i value for the next iteration of # the loop. current_ratio *= r # At this point, total is r^0 + r^1 + ... + r^n. Now we multiply it by a # to get the total sum for the n terms we evaluated. total *= a print 'A geometric series with', n, 'terms with a =', a, 'and r =', r, 'evaluates to', total main()