Coding Bat: Python. List-1

All solutions were successfully tested on 16 April 2013.

first_last6:

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

same_first_last:

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

make_pi:

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

common_end:

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

sum3:

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.

rotate_left3:

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

reverse3:

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”.

max_end3:

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

sum2:

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

middle_way:

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

make_ends:

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

has23:

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

Do you remember what this looked like in Java?

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

  1. Gud

    I know my code is a silly one – but why is it wrong for has23([4, 5]) (gives True???)
    def has23(nums):
    if nums[0] or nums[1]== 2 or 3:
    return True
    else:
    return False

    Reply

Leave a Reply to Gregor Ulm Cancel 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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.