-4

I am looking for an explanation to the solution to the front_back google python exercise. Specifically, I do not understand why the % symbol (placeholder?) is used. I also do not understand why the length of the strings are divided by 2. Especially since 2 does not equal 1 (2==1??)

The problem/solution is as follows:

# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
#  a-front + b-front + a-back + b-back
def front_back(a, b):
  # +++your code here+++
  # LAB(begin solution)
  # Figure out the middle position of each string.
  a_middle = len(a) / 2
  b_middle = len(b) / 2
  if len(a) % 2 == 1:  # add 1 if length is odd
    a_middle = a_middle + 1
  if len(b) % 2 == 1:
    b_middle = b_middle + 1 
  return a[:a_middle] + b[:b_middle] + a[a_middle:] + b[b_middle:]
  # LAB(replace solution)
  # return
  # LAB(end solution)

THANK YOU!

  • 3
    % is not a placeholder. It's the modulo operator. The comment above it's first use tells you what that line is doing. And the comments tell you exactly why division by 2 is being done. I'd suggest you find one of the tutorials for Python. There's a list of them at python.org. (At the very least, you should read the comments in the code you've posted. They explain things very clearly, but you have to actually read the words in them.) – Ken White Jun 26 '17 at 22:24
  • @KenWhite reading the those words only makes sense if you are familiar with what the modulo operator is. This was a reasonable question. – SandPiper Jul 25 '17 at 16:31

1 Answers1

1

It seems the statement you're most confused about is if len(a) % 2 == 1:. The % sign in this case means division with remainder (modulo). So if the length of the string were odd then dividing the length by 2 has a remainder 1 and if the length were even the remainder is 0. The if statement checks if the remainder is 1 and therefore if the length is odd.

Earlier the length strings are divided by 2 to find the middle position of the strings. However, since len(string) and 2 are both integers, python performs integer division and rounds the result down to an integer, which is why you need to add back the extra spacing unit with if statement if the length were odd.

The final statement of the code then uses the slice syntax to concatenate the string halves based on the positions found previously.

mugwump
  • 436
  • 1
  • 4
  • 10