All solutions were successfully tested on 17 April 2013.
cigar_party:
def cigar_party(cigars, is_weekend): if is_weekend: return cigars >= 40 return 40 <= cigars <= 60
Pay attention to the last line! In Python it is possible to concatenate comparisons, just like you would do it in mathematics. This can lead to much cleaner code. In my opinion, the solution from the website is worse, but not just for that reason alone:
def cigar_party(cigars, is_weekend): if is_weekend: return (cigars >= 40) else: return (cigars >= 40 and cigars <= 60)
date_fashion:
def date_fashion(you, date): if you <= 2 or date <= 2: return 0 if you >= 8 or date >= 8: return 2 return 1
squirrel_play:
def squirrel_play(temp, is_summer): if is_summer: return 60 <= temp <= 100 return 60 <= temp <= 90
caught_speeding:
def caught_speeding(speed, is_birthday): if is_birthday: speed -= 5 if speed <= 60: return 0 if 60 < speed <= 80: return 1 return 2
sorta_sum:
def sorta_sum(a, b): if 10 <= a + b < 20: return 20 return a + b
It is not necessary to put “a + b” in line 2 inside parentheses due to the rules of precedence of operators. A less experienced human reader might be able to parse this line more quickly with parens, though. However, you shouldn’t assume that you write code for a complete beginner.
alarm_clock:
def alarm_clock(day, vacation): if not vacation: if 1 <= day <= 5: return '7:00' return '10:00' if 1 <= day <= 5: return '10:00' return 'off'
love6:
def love6(a, b): return a == 6 or b == 6 or (a + b) == 6 or abs(a - b) == 6
What, this looks ugly you say? I completely agree, and there is a much more pleasant solution:
def love6(a, b): return 6 in [a, b, a + b, abs(a - b)]
in1to10:
def in1to10(n, outside_mode): if not outside_mode: return n in range(1, 11) return n <= 1 or n >= 10
near_ten:
def near_ten(num): # return 0 <= (num % 10) <= 2 or 8 <= (num % 10) <= 10 return num % 10 in [0,1,2,8,9,10]
Again, do you go for ugly or nice and clean?
Hey Greg
Is 10 necessary in near_ten return? Multiplication of 10 cannot have mode bigger than 9 if I’m correct.
You are right, this still works without ten