vendredi 4 août 2017

codingbat python two_two function

I've been working on a codingbat problem called two_two using Python. This is from the site:

Given a list of ints, return true if every 2 that appears in the list is next to another 2.

two_two([4, 2, 2, 3]) → True

two_two([2, 2, 4]) → True

two_two([2, 2, 4, 2]) → False

two_two([1, 3, 4]) ==> True (I added this one for clarity)

I got this to work, but it was a rather long solution and I'm curious about how to simplify it. As you can see in my comments, I also had problems getting a for loop to recognize the last number in a list if it was a 2. Here is the code:

def two_two(nums):
  # lists with no 2's should return true
  if 2 not in nums:
    return True

  # I added this because my iteration below could not
  # recognize the final 2 in a list
  if nums[-1] == 2 and nums[len(nums) - 2] != 2:
    return False

  # I had to add this because of the same problem
  count = 0  
  for v in nums:
    if v == 2:
      count += 1
  if count == 1:
    return False

  # why does this not recognize the final 2 in a list?
  # is there an easier way to do this than my approach?
  Boolian_list = []
  for i in range(len(nums)-1):
    # if the element, as well as that on either side is 2:
    if nums[i] == 2 and (nums[i+1] == 2 or nums[i-1] == 2):
      # append a list with T, for True
      Boolian_list.append('T')
    # if element is 2, but neither to either side is a 2:
    elif nums[i] == 2 and not (nums[i+1] == 2 or nums[i-1] == 2):
      # append the list with F, for False
      Boolian_list.append('F')
  if 'F' in Boolian_list:
    return False
  elif 'F' not in Boolian_list:
    return True

  # all other conditions are false
  return False

Your help is much appreciated!

Aucun commentaire:

Enregistrer un commentaire