Coding Bat: Python. Warmup-2

All solutions were successfully tested on 13 April 2013.

string_times:

def string_times(str, n):
  return str * n

front_times:

def front_times(str, n):
  if len(str) < 3:
    return str * n
  return str[:3] * n

string_bits:

def string_bits(str):
  result = ''
  for n in range(0, len(str)):
    if n%2 == 0:
      result += str[n]
  return result

string_splosion:

def string_splosion(str):
  result = ''
  for n in range(0,len(str)+1):
    result += str[:n]
  return result

last2:

def last2(str):    
  count = 0
  for i in range(len(str)-2):
    if str[i:i+2] == str[-2:]:
      count += 1   
  return count

Below I show the solution from the website, which is overambitous since there is no need to specifically process cases in which the input string is too short. The reason is that the for loop takes the length of the string into account. If the range was given as an absolute number, say, range(10), then a separate check that the string is long enough would have been necessary.

def last2(str):
  # Screen out too-short string case.
  if len(str) < 2:
    return 0
  
  # last 2 chars, can be written as str[-2:]
  last2 = str[len(str)-2:]
  count = 0
  
  # Check each substring length 2 starting at i
  for i in range(len(str)-2):
    sub = str[i:i+2]
    if sub == last2:
      count = count + 1

  return count

array_count9:

def array_count9(nums):
  count = 0
  for element in nums:
    if element == 9:
      count += 1
  return count

Please note that Python allows you to conveniently name variables, which makes the resulting code a lot more readable. In Java you would probably stick to variable names like “i” due to the fact that you have to repeat them so often. Below is a solution in Java to illustrate this issue. Imagine you would have written “element” instead of “i”:

public int arrayCount9(int[] nums) {
	int result = 0;
	for (int i = 0; i < nums.length; i++) {
		if (nums[i] == 9)
			result++;
	}
	return result;
}

array_front9:

def array_front9(nums):
  for element in nums[:4]:
    if element == 9:
      return True
  return False

Again, there is a slight inconvenience in the solution given on Coding Bat:

def array_front9(nums):
  # First figure the end for the loop
  end = len(nums)
  if end > 4:
    end = 4
  
  for i in range(end):  # loop over index [0, 1, 2, 3]
    if nums[i] == 9:
      return True
  return False

It is superfluous to consider the length of the array since the slice [:4] will be processed at most up to but not including position 4. If the array is shorter, the procedure will simply stop. I have seen pythonistas defend similar code by referring to the Zen of Python, particularly the line “Explicit is better than implicit.” However, I consider this to be a bizarre interpretation. If you write code like that you only show that you have not yet “grokked” Python and instead translate from another language. You can write Java in Python, but not the other way round, so if you’ve got the option to write more elegant code, why wouldn’t you want to make use of that opportunity?

array123:

def array123(nums):
  for i in range(len(nums)-2):
    if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3:
      return True
  return False

But, wait, this can be done more nicely:

def array123(nums):
  for i in range(len(nums)-2):
    if nums[i:i+3] == [1,2,3]:
      return True
  return False

string_match:

def string_match(a, b):
  min_length = min(len(a), len(b))
  
  count = 0  
  for i in range(min_length-1):
    if a[i:i+2] == b[i:i+2]:
      count += 1
  return count

3 thoughts on “Coding Bat: Python. Warmup-2

  1. s

    for array_font9 why does the following not work:

    def array_front9(nums):
    for i in nums[:4]:
    if i == 9:
    return True
    else:
    return False

    Reply
  2. LSL

    For array123, do you know why this one line solution does not work?

    return bool(True for i in range(len(nums) – 2) if nums[i: i + 3] == [1, 2, 3])

    It works like this for me and suits how I like to style things:

    has_seq = False

    for i in range(len(nums) – 2):
    if nums[i: i + 3] == [1, 2, 3]:
    has_seq = True
    break

    return has_seq

    So not sure why a one line return not possible. Any help you could give would be great!

    Reply

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.

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