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