Coding Bat: Python. Warmup-1

All solutions were successfully tested on 13 April 2013.

sleep_in:

def sleep_in(weekday, vacation):
  return not weekday or vacation

As you can already see, it’s pleasant to write Python code, and this language is very readable, too. Just compare this method with the equivalent in Java:

public boolean sleepIn(boolean weekday, boolean vacation) {
  return (! weekday || vacation);
}

monkey_trouble:

def monkey_trouble(a_smile, b_smile):
  return a_smile and b_smile or not a_smile and not b_smile

sum_double:

def sum_double(a, b):
  if a == b:
    return a * 4
  return a + b

diff21:

def diff21(n):
  if n > 21:
    return abs(n-21) * 2
  return abs(n-21)

parrot_trouble:

def parrot_trouble(talking, hour):
  return talking and (hour < 7 or hour > 20)

makes10:

def makes10(a, b):
  return a + b == 10 or a == 10 or b == 10

near_hundred:

def near_hundred(n):
  return abs(n-100) <= 10 or abs(n-200) <= 10

pos_neg:

def pos_neg(a, b, negative):
  if negative:
    return a < 0 and b < 0
  return a * b < 0

I took a shortcut in the last line since the result will be negative if one of the numbers is negative, and the other positive. The sample solution on the website is more verbose:

def pos_neg(a, b, negative):
  if negative:
    return (a < 0 and b < 0)
  else:
    return ((a < 0 and b > 0) or (a > 0 and b < 0))

not_string:

def not_string(str):
  if str[:3] == "not":
    return str
  return "not " + str

missing_char:

def missing_char(str, n):
  return str[:n] + str[n+1:]

front_back:

def front_back(str):
  if len(str) == 0 or len(str) == 1:
    return str
  return str[-1] + str[1:-1] + str[0]

front3:

def front3(str):
  if len(str) < 3:
    return str * 3
  return str[:3] * 3

Leave a Reply

Your email address will not be published. Required fields are marked *

Spammer prevention; the answer is an integer: * Time limit is exhausted. Please reload CAPTCHA.