Categories
Coderbyte Data Structures and Algorithms Easy Maths Python String manipulation Uncategorized

[Coderbyte] – Dash Insert [Easy]

This problem asks us to add a dash between each pair of odd numbers in the given string. A more detailed description from Coderbyte:

Have the function DashInsert(str) insert dashes (‘-‘) between each two odd numbers in str. For example: if str is 454793 the output should be 4547-9-3. Don’t count zero as an odd number. 

The first step is to create a new variable that will store the dashed number. A variable was also created to store the last digit from the string, as the loop will finish at the second last position. The last digit is concatenated to the final dashed number.

    dashed = ''
    lastNum = a[len(a)-1]

The next step is to loop over the string and check whether the current digit and the next digit are odd. If both are odd numbers, add a dash between them. For readability purposes, I created two variables in the loop that stores the current position and the next position.

    for position in range(len(a)-1):
        digit = int(a[position])
        nextDigit = int(a[position+1])
        
        if digit % 2 != 0 and nextDigit % 2 != 0:
            dashed = dashed + str(digit) + '-'
        else:
            dashed = dashed + str(digit)

That is done by the above code. If the current digit is odd AND the next digit is odd, add a dash after the current digit. If not, add the current digit to the string. We can test if a number is odd by checking the remainder of the division. If the remainder is not 0, the digit is odd. The loop stops when it reaches the second last digit.

The last step is to return the dashed number. As I have said previously, the loop stops at the second last digit, so when the number is returned, the last digit needs to be added as well. The full solution is below:

def DashInsert(a):
    dashed = ''
    lastNum = a[len(a)-1]
    
    for position in range(len(a)-1):
        digit = int(a[position])
        nextDigit = int(a[position+1])
        
        if digit % 2 != 0 and nextDigit % 2 != 0:
            dashed = dashed + str(digit) + '-'
        else:
            dashed = dashed + str(digit)
            
            
    return dashed + lastNum

The solution provided by Coderbyte is as follows:

def DashInsert(str): 

  # convert the string into a list
  # with each element being a single number
  arr = list(str)

  # loop through the list of numbers and add a dash if 
  # the current number and the next number are odd
  # NOTE: to determine if a number is odd we  
  # divide by 2 and check if there is a remainder
  # e.g. 4 / 2 = 0 remainder
  # e.g. 5 / 2 = 1 remainder
  # e.g. 9 / 2 = 1 remainder
  for i in range(0, len(arr)-1):
    if (int(arr[i]) % 2 != 0 and int(arr[i+1]) % 2 != 0):
      arr[i] = arr[i] + '-'
    
  # join the numbers into a final string
  return "".join(arr)

Leave a Reply

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