All solutions were successfully tested on 17 April 2013.
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)
def date_fashion(you, date): if you <= 2 or date <= 2: return 0 if you >= 8 or date >= 8: return 2 return 1
def squirrel_play(temp, is_summer): if is_summer: return 60 <= temp <= 100 return 60 <= temp <= 90
def caught_speeding(speed, is_birthday): if is_birthday: speed -= 5 if speed <= 60: return 0 if 60 < speed <= 80: return 1 return 2
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.
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'
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)]
def in1to10(n, outside_mode): if not outside_mode: return n in range(1, 11) return n <= 1 or n >= 10
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?