Homework 3, due Monday, Feb 11
You are to submit one file containing the functions
temperance(), csearch() (and collatz() again) and circlerandom().
1. Write a function temperance(t) to convert from Fahrenheit to words (that is, strings):
2. Write a function csearch(lo, hi, thresh) that lists all the numbers n between lo and hi (that is, n in range(lo, hi)) for which collatz(n) > thresh. For each number n, also list collatz(n).
Observation: for this to work, collatz() has to return its value, but not print anything.
4. Write a function circlerandom() in which you choose 10,000 random points (x,y) in the unit square 0<=x<=1, 0<=y<=1. For each point, calculate whether or not it is inside the circle of radius 1 centered at the origin. The function should return the fraction of such points.
Is it close to 𝜋/4? That is the ratio of the areas of the circle sector to the square. (𝜋/4 is about 0.7853981633974483. Alternatively, return 4 times the ratio, and see if it's close to 𝜋)
Monday:
d = dict()
d['one'] = 1
d['three'] = 3
d['two'] = 2
d
What does this do:
for i in d:
print(i)
What can you do with a dictionary?
1.12.2
numberFormat = 'Count in Spanish: {one}, {two}, {three}, ...' withSubstitutions = numberFormat.format(one='uno', two='dos', three='tres') print(withSubstitutions)
Note that format here is a dot-function.
d = dict()
d['one'] = 'uno'
d['two'] = 'dos'
d['three'] = 'tres'
numberFormat.format(**d)
d.keys()
d.values()
d.items()
1.14.3:
locals()
x = 2.71828182845904523536
'longer: {x:.5f}, shorter: {x:.3f}.'.format(**locals())
if statements on the same line
if x==3: x=5
if versus if-else2.1: strings:def calcWeeklyWages(totalHours, hourlyWage): '''Return the total weekly wages for a worker working totalHours, with a given regular hourlyWage. Include overtime for hours over 40. ''' if totalHours <= 40: totalWages = hourlyWage*totalHours else: overtime = totalHours - 40 totalWages = hourlyWage*40 + (1.5*hourlyWage)*overtime return totalWages def main(): hours = float(input('Enter hours worked: ')) wage = float(input('Enter dollars paid per hour: ')) total = calcWeeklyWages(hours, wage) print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.' .format(**locals())) main()
upper()
lower()
dir('')
count()
s[3]
s[1:3]
split(separator)
join()
Friday:
resubmission rules
collatz()
return vs print
circlerandom()