Coding Bat: Python. List-1

All solutions were successfully tested on 16 April 2013.


def first_last6(nums):
  return nums[0] == 6 or nums[-1] == 6


def same_first_last(nums):
  return len(nums) >= 1 and nums[0] == nums[-1]


def make_pi():
  return [3, 1, 4]


def common_end(a, b):
  return a[0] == b[0] or a[-1] == b[-1]


def sum3(nums):
  #return nums[0] + nums[1] + nums[2]
  return sum(nums)

Either way works. The version I’ve commented out is less elegant, though.


def rotate_left3(nums):
  return [nums[1], nums[2], nums[0]] 


def reverse3(nums):
  #return [nums[2], nums[1], nums[0]]
  return nums[::-1]

Again, the second version is more elegant or, as some phrase it, more “pythonic”.


def max_end3(nums):
  m = max(nums[0], nums[2])
  return [m, m, m]

For matters of comparison, here is the solution from the website:

def max_end3(nums):
  big = max(nums[0], nums[2])
  nums[0] = big
  nums[1] = big
  nums[2] = big
  return nums

It is less expressive and, frankly, a bit painful to look at. A much nicer way to assign “big” to three variables at once would be one of the two following ways:

def max_end3(nums):
  big = max(nums[0], nums[2])
  #nums[0], nums[1], nums[2] = big, big, big
  nums[0], nums[1], nums[2] = (big, ) * 3
  return nums


def sum2(nums):
  if len(nums) == 0:
    return 0
  if len(nums) == 1:
    return nums[0]
  return nums[0] + nums[1]


def middle_way(a, b):
  return [a[1], b[1]]


def make_ends(nums):
  return [nums[0], nums[-1]]


def has23(nums):
  return 2 in nums or 3 in nums

Do you remember what this looked like in Java?

5 thoughts on “Coding Bat: Python. List-1

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.